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

Tips for displaying a placeholder image within the Next.js image component

I am currently facing an issue with displaying images from API calls. To handle situations where there are no images or errors, I have implemented a code snippet which includes a placeholder image. However, the implementation seems to not be functioning as ...

Transferring a Sharepoint 2010 List Item between folders

Currently, I am facing an issue while attempting to transfer a list item from one folder to another. Despite utilizing a code that I discovered (the link to the source of the code can be found below), I keep encountering an error message stating "Value doe ...

Running multiple JavaScript servers simultaneously can be achieved by utilizing specific tools and

Currently, I am working on developing a Discord bot and have encountered some issues along the way that all required the same solution. The fix involved running separate batch files instead of running everything in my main file (index.js). I opted to use n ...

Solving repeated function firing with ng-checked in an AngularJS ng-repeat loop

In the HTML code below, there is an ng-repeat that creates checkboxes: <span ng-repeat="name in $ctrl.widgetSelectorNames" class="widget-selectors"> <label class="checkbox" for="{{name}}"> <input type="checkbox" value="{ ...

Steps for organizing a particular key in a map

I need assistance sorting my map based on the "time" value, but so far, I haven't been successful in finding a solution after searching online extensively. If anyone has any insights or recommendations, please share them with me. This is how my Map ...

The display of options in React Bootstrap typeahead is not functioning properly

When I try to implement React Bootstrap Typeahead, the options do not appear in the Typeahead component upon page load. Here is a snippet of my code: const React = require('react'); ... (code continues) The options are generated as follows: [ ...

Encountering a "Window is undefined" error while trying to load a node_module package within a

I am attempting to incorporate the pickr package (a color picker library) into my nuxt.js application. However, I am encountering an error during import, specifically "window is undefined". Below is the code snippet: <script> import Pickr from &apo ...

Transforming a string representation of a nested array into an actual nested array with the help of JavaScript

My database stores a nested array as a string, which is then returned as a string when fetched. I am facing the challenge of converting this string back into a nested array. Despite attempting to use JSON.parse for this purpose, I encountered the following ...

Is there a way to display two words side by side in React components?

I previously had the following code: projectName: project.get('name') === 'default' ? 'No Project' : project.get('name') In the render() method, it was written like this: <div className='c-card__projects&ap ...

Preventing users from retaking the quiz

As I work on developing a quiz for a website using Express, Passport, Handlebars, and Mongoose/MongoDB, I'm facing an issue with preventing users from taking the same quiz more than once. This particular quiz is designed to be taken only once, so once ...

Struggling to integrate font-awesome into my Vue.js project

Observation: The stars should be displayed using the Font Awesome font. Issue: An error font is being displayed instead of Font Awesome, indicating that it is not being loaded properly. Hello. I am encountering problems with including Font Awesome in my p ...

Locate the nearest span element and update its CSS class

On my page, there is a section with the following code: <h5 class="text-center" id="findStore" style="width:260px"> <a data-toggle="collapse" data-parent="#accordion" href="#@item.ProductId" aria-expanded="true" aria-controls="@item.ProductId ...

"Although both jQuery and PHP are capable of setting the element attribute, it is only PHP that functions successfully

I have been trying to set an element attribute to adjust the range of a slider. Initially, I used ajax to fetch data from a php file and assign it to the attribute. The slider looked good with the value but unfortunately, it wasn't functioning as expe ...

Utilizing PrimeVue Toast to showcase rich HTML content

Looking for a way to showcase a link in a primevue toast message without using the v-html directive or triple brackets. Anyone have any alternative solutions to suggest? ...

Is there a way to transform an Array or Object into a new Object mapping?

When using the map method in JavaScript, it typically returns an Array. However, there are instances where I would like to create an Object instead. Is there a built-in way or a simple and efficient implementation to achieve this? Solutions using jQuery ar ...

data is currently being uploaded to the storage, however, the grid is not displaying any

After loading JSON data into the store, I am unable to see any data in the grid. Can someone please point out what I might be doing wrong? Here's the code snippet for the grid: { xtype: 'gridpanel', ...

Electron JS-powered app launcher for seamless application launching

Currently, I am working on a project to develop an application launcher using HTML, CSS, and JS with Electron JS. Each application is linked through an a href tag that directs users to the respective application path. If a normal link is used in the a hr ...

Incorrect positioning of arrow in OverlayPanel (PrimeVue)

I have been experimenting with overlay panels in the PrimeVue framework, and I've encountered a peculiar issue that I can't seem to resolve. On the demo page, the arrow is positioned on the left side: https://i.stack.imgur.com/Gn3qe.png Howeve ...

Tips for avoiding unnecessary re-renders

The component I created sends props to both the checkbox and range components. During testing, I noticed that when a change was made in the range component, the checkbox also re-rendered even though it wasn't changed, and vice versa. Issue: When ...

Using Regex instead of the method resulted in logging an unexpected output, displaying the matched text as $& and the

I have a regular expression that I'm using with the .replace method to extract paragraphs from a string and add them to an array. I've been struggling with my getValues function; when I logged Match and Group1 to the console, I got unexpected re ...