Request denied due to CORS policy, despite setting Access-Control-Allow-Origin to *

My console is showing an error when I try to make a POST request on my website. The error states: Access to XMLHttpRequest at 'https://exp.mysite.com/i_l' from origin 'https//frontend.mysite.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

It's interesting to note that I have the same setup working fine on my local PC.

Below is the configuration of my server.js file on the Express side for CORS:

const path = require('path');
const fs = require('fs');
const express = require('express');
const multer = require('multer');
const bodyParser = require('body-parser')

const app = express();
const router = express.Router();

const DIR = './uploads';

let storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, DIR);
  },
  filename: (req, file, cb) => {
    cb(null, file.fieldname + '-' + Date.now() + '.' + path.extname(file.originalname));
  }
});

let upload = multer({ storage: storage });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


app.use(function(req, res, next) {
 res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

  next();
});

const PORT = process.env.PORT || 3001;

app.listen(PORT, function () {
  console.log('Node.js server is running on port ' + PORT);
});

Answer №1

To effectively implement CORS on your express server, consider using the cors middleware.

Follow these steps. First:

npm install cors --save

Then:

...
const cors = require('cors')

const app = express();
...

app.use(cors());

...

Answer №2

To make use of Access-Control-Allow-Credentials, it's important to note that the wildcard * cannot be used. You must specify the exact ORIGIN:

res.setHeader("Access-Control-Allow-Origin", "https//frontend.mysite.com");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to conceal the input div without compromising the functionality in Angular 14

Here is the provided HTML code for scanning a barcoder and assigning it to the barCodeNumber variable. The onChange() function will be called once the barcode is scanned. Question: How can I hide the div on the UI while still allowing the function to work ...

Moving the marker does not update the address

When the dragend event is triggered, the Getaddress function will be called in the following code: Getaddress(LastLat, LastLng , marker,source){ this.http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng='+LastLat+ &apos ...

Receiving a WAV audio file via HTTP POST on a Node/Express server

I am attempting to transfer an audio file named audio.wav using cURL to my Express server. The cURL request I am using is as follows: curl -X POST --data-binary @"audio.wav" -H "Content-Type: audio/wav" localhost:3000/extract_indicators/audio/darksigma ...

Could someone please provide guidance on how to assign a datepicker value to my form using ng-model?

Check out datepicker.ts import { Component, HostListener, ViewChild } from '@angular/core'; import { BsDatepickerDirective } from 'ngx-bootstrap/datepicker'; @Component({ selector: 'demo-date-picker-hide-on-scroll', ...

"Passing an Empty String as Input in a NodeJS Application

app.post('/register',function(req,res){ var user=req.body.username; var pass=req.body.password; var foundUser = new Boolean(false); for(var i=0;i<values.length;i++){ //if((JSON.stringify(values[i].usernames).toLowerCase==JSON. ...

Resetting Cross-Site Request Forgery (CSRF

Struggling to integrate Django's csrf with Angular 6? Check out this insightful thread I came across. It seems that Django changes the token on login, which makes sense as I can register and login using post requests but encounter issues posting after ...

strategies for chaining together multiple observables with varying data types and operations

Hey everyone! I'm facing a situation where I have a form with multiple select types, and the options for these inputs are coming from an API. I then take the data emitted from the HTTP request observable and feed it into my FormGroup, and everything i ...

Is storing user permissions in Redis a smart move?

Lately, I've been focusing on enhancing the performance of my app. I'm considering caching user data and permissions in Redis. Currently, every time a user creates a post or uploads a file, the app checks the database to verify the user's ex ...

What is the purpose of mapping through Object.keys(this) and accessing each property using this[key]?

After reviewing this method, I can't help but wonder why it uses Object.keys(this).map(key => (this as any)[key]). Is there any reason why Object.keys(this).indexOf(type) !== -1 wouldn't work just as well? /** * Checks if validation type is ...

Issue with tsconfig compilerOptions "module": "system" not functioning as expected

During my journey with the Angular2 5-minute tutorial, I encountered an issue with the "system" module in the tsconfig file. Despite having systemjs as a node_module, I faced an error message saying System is not defined at the beginning of the compiled js ...

Firebase allows for the updating of an object within a nested array

Within Firestore, I have a Document that includes a property named "items" which is of type array. This array consists of ShoppingItem objects with the specified structure: export class ShoppingItem { id?: string; name: string; checked = false; } To ...

Is it possible to navigate to the Angular component that defines a tag in VSCode by simply clicking on the tag?

In my current Angular project in VSCode, I often find myself wanting to delve deeper into specific tags that I encounter while coding. For instance, if I stumble upon a tag like <display-active-users>, I usually have to go through the process of sea ...

Develop a TypeScript utility function for Prisma

Having trouble inferring the correct type for my utility function: function customUtilityFunction< P, R, A extends unknown[] >( prismaArgs /* Make "where" field optional as it is already defined inside findUnique method below */, fn: ( pris ...

Having trouble installing Popper.js?

I have encountered an issue while attempting to install popper.js in my angular project. ng new <<project>> cd <<project>> npm install popper --save npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules&b ...

The array is not empty but the length is being displayed as zero

I am facing an issue in my project where I can successfully print the array in console, but I am unable to retrieve the length and access the first element. Here is the code snippet: checkout.component.ts: ngOnInit() { this.booksInCheckout = this.ch ...

Retrieve specific data from a subdocument in Mongoose using a query with filtering capabilities

I'm facing an issue where I want to extract a specific subdocument from a parent document based on a certain field value, but my current query is returning all subdocuments instead of just the one I need. I am trying to filter by the candidateId field ...

Can you please explain the significance of classes <T> and <U> in Angular 2?

After diving into the Angular 2 TypeScript documentation, I have come across these two classes frequently. Can someone provide a detailed explanation of what they are? One example code snippet from the QueryList API documentation showcases: class QueryLi ...

Execute consecutive Angular2 functions in a sequential manner, one following the next

In my Angular2 project, I have a service that fetches data for dropdown menus on a form. However, when I call this service multiple times with different parameters in the form component initialization, only the last call seems to work, overriding the previ ...

Is it possible to utilize solely JsonSchema with Mongoose?

I've built an API using express, MongoDB, and AJV validation for validating incoming requests. // JSONSchema var recordJsonSchema = { type: "object", properties: { name: { type: "string" }, idNumber: { type: "number" }, ...

Showing an error message with matInput instead of a form control - is this possible?

Within my Material table, I am utilizing the following code: <ng-container matColumnDef="columnDef"> <th mat-header-cell *matHeaderCellDef>Column heading</th> <td mat-cell *matCellDef="let row"> <mat-form-field> ...