Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies.

In an attempt to resolve this, I set the headers in the middleware following suggestions from StackOverflow:

router.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    console.log('Something is happening.');
    next(); // proceed to the next routes
});

However, this did not fix the problem. So, I looked into a CORS NPM package: https://www.npmjs.com/package/cors

I followed the installation guide and added it to my solution:

....
var cors = require('cors');
....
app.use(cors());
app.options('*', cors())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

But still no luck.

I am running out of ideas and unsure about what could be causing the issue.

Here is the client-side code snippet:

login() {
      if(this.input.username != '' && this.input.password != '') {
          //Execute Axios here

          axios.post('http://localhost:8080/api/user/login',{
            username:this.input.username,
            password:this.input.password   
          })
            .then(function (response) {
                // handle success
                console.log(JSON.stringify(response.data));
                console.log(response.status);
                console.log(response.headers);
                //Router.push('Dashboard')
            })
            .catch(function (error) {
                // handle error
                console.log(JSON.stringify(error.data));
                console.log(error.status);
                console.log(error.headers);
            })
            .then(function () {
                // always executed
            });
      } else {
          console.log('A username and password must be present')
      }
}

The post method itself:

router.route('/user/login/')
    .post(function(req, res) {
        var user = new User();
        user.username = req.body.username;
        user.password = req.body.password;
        User.findOne({ username: user.username}, function(err, dbuser) {
            if (err)
                res.send(err);
                console.log('Error');

            bcrypt.compare(user.password, dbuser.password, function(err, compareResult) {
                console.log('Match!')
                
                var token = jwt.sign({ username: user.username }, secret, {
                    expiresIn: 86400 
                });
                res.cookie("test", user.username);
                res.status(200).send({ auth: true, token: token });
                console.log(token);
            });
        });
});

Answer №1

Here are the custom settings I implement when utilizing the cors module to handle CORS-related functionalities:

const corsOptions = {
  origin: true,
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  credentials: true,
  preflightContinue: true,
  maxAge: 600,
};
app.options('*', cors(corsOptions));
app.use(cors(corsOptions));

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

Allow-Origin-Control, handler.php for emails, and form validation script

I encountered a strange bug recently. There's been some issues with the HTML5 template I downloaded, specifically related to the contact form and MailHandler.php file. Despite having both files in the same directory, when inspecting element in Chrome, ...

Bar graph constructed using a pair of div elements

I extracted two values from an array: $target = $data->data[2][32][3]; For this particular example, $target = 9.83%. $clicks = $data->data[1][32][3]; And in this case, $clicks = 7.15%. I have created a bar-like chart using three main div elements ...

Extracting specific key-value pairs from JSON data

Working with JSON data, I encountered a need to pass only specific key-value pairs as data to a component. Initially, I resorted to using the delete method to remove unwanted key-value pairs, which did the job but left me feeling unsatisfied. What I truly ...

Is it possible to import a component from a production build of create-react-app?

Has anyone tried importing a component from a production build of create-react-app? Situation: I have one CRA project that has been built for production. Inside this project, there is a component named ExampleButton. Now, I am working on a second CRA pro ...

Is Angular Translate susceptible to race conditions when using static files for multi-language support?

Currently utilizing angular translate with the static files loader for implementing multiple languages in my project. However, I've encountered a problem where the loading of language files sometimes takes longer than loading the actual view itself, l ...

Start up a NodeJs Express application on the main URL using Nginx

Scenario I have a unique application built with PHP that is currently hosted on a domain called example.com. It runs on an nginx server. Recently, I developed a new NodeJS express application that needs to be deployed on example.com/nodeApp (without the t ...

The images on the website fail to load, while other static files are loading without any issues

I've been struggling with a confusing issue for hours now. I have a simple website with a chat application running on an express server. When accessed on localhost, everything works perfectly fine - images load, css and js files are served without any ...

The replacement of className in inline SVG is not permitted (Error: 'Cannot read property 'className.replace' of undefined')

I've hit a roadblock trying to manipulate classes within an SVG document to modify the rect elements. The code works smoothly on divs in an external document, but I've tried several other solutions as well – all listed below. I'm still rel ...

Guidance on implementing a source map in a Node.js VM

Currently, I am analyzing JavaScript bundled source code in Node.js using the following snippet of code: const javascriptCode = "..." const javascriptSourceMap = "..." const wrapper = NativeModule.wrap(javascriptCode); const script = ne ...

Tips on retrieving a value nested within 3 layers in Angular

In my Angular application, I have three components - A, B, and C. Component A serves as the main component, Component B is a smaller section nested inside A, and Component C represents a modal dialog. The template code for Component A looks something like ...

Utilizing npm packages with grunt: A guide

Initially, when I was working with node.js without grunt, I simply had to write the code below to import an external module. var express = require('express'); However, after transitioning to grunt, I attempted to utilize the qr-image module in ...

Exploring cross-site session management using a NodeJS/Passport/Express backend integrated with a Polymer frontend

Currently, I have a node/express/passport backend running on port 3001 that I am accessing directly from the browser for authentication purposes. It successfully authenticates and manages access to protected URLs. The frontend is built using Polymer and is ...

Showing the values of two distinct select boxes in a URL

Here are both select boxes, the goal is to display selected values from both in the URL. This can be achieved by displaying them like this: e.g www.example.com#135+#140 OR www.example.com#135&140 (The order of values doesn't matter as long as bot ...

What is the reason behind using angle brackets to access the initial value of an array with a variable inside?

I've been experimenting with this technique several times, but I still can't quite grasp why it works and haven't been able to find an answer. Can someone please explain? let myArray = [0, 1] let [myVar] = myArray console.log(myVar) // outpu ...

Is there a way to determine if the current path in React Router Dom v6 matches a specific pattern?

I have the following paths: export const ACCOUNT_PORTAL_PATHS = [ 'home/*', 'my-care/*', 'chats/*', 'profile/*', 'programs/*', 'completion/*', ] If the cur ...

Having trouble converting the file to binary format in order to send it to the wit.ai api through node.js

I am having trouble converting an Audio file to Binary format for sending it to the Wit.AI API. The node.js platform is being used for this purpose. On the front-end, user voice is recorded using the Mic-recorder Module. Any guidance or suggestions would b ...

Error code 400 encountered during an HTTP POST request - issue stems from incorrect design of views and serializers

I keep encountering the following error: POST http://127.0.0.1:8000/api/creator_signup/ 400 (Bad Request) Every time I try to send data from my AngularJS application to my Django backend. When making a POST request, I used the following code (): fun ...

I have a JavaScript code stored as a string that I need to transform into plain JavaScript

If I have a variable in string format, for example suppose there is a JavaScript code inside it: var string="function myFunction(a,b){return a*b;}"; I want to convert this into pure JavaScript code format like so: function myFunction(a, b) { return ...

Is It Best to Override Behavior in a Directive?

Having two directives that display lists of documents, one for user-favorited documents and the other for user-pinned documents. The criteria for displaying these documents depend on the values of "pinned" and "favorite" within each document object: docum ...

Only one session allowed per user in Passport JS

As I dive into using Passport JS, I have successfully implemented user login and page restriction based on user roles. However, a concern arises when I realize that users can log in from multiple devices simultaneously using the same credentials. This shar ...