0

I'm trying to send a post request to a node server using axios, here's what I've done in react-js.

axios.post('http://localhost:5000', {
      firstName: 'Finn',
      lastName: 'Williams'
    })
    .then((response) => {
      console.log(response);
    }, (error) => {
      console.log(error);
    });

And here's what I've done in the server.

const express = require('express')

const app = express()
const port = 5000;

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Every time I send the request, I get the following message in the console Access to XMLHttpRequest at 'http://localhost:5000/' from origin 'http://localhost:3000' 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.

What should I do to fix that?

Migo101
  • 3
  • 1
  • 2
  • The ports are different, they count as different origins. – Daniel W. May 18 '21 at 10:35
  • 1
    Does this answer your question? [How to enable cors nodejs with express?](https://stackoverflow.com/questions/43150051/how-to-enable-cors-nodejs-with-express) – Daniel W. May 18 '21 at 10:39

4 Answers4

0

You can install the cors

  • npm install cors --save

after that you can add this code on server file

var cors = require('cors')

app.use(cors()) // Use this after the variable declaration
Ankita Kuchhadiya
  • 1,255
  • 6
  • 16
  • When I did that, I got POST http://localhost:5000/ 404 (Not Found) – Migo101 May 18 '21 at 10:37
  • You need to post to port `5000` and allow from origin with port `3000`. Different ports = different origin. – Daniel W. May 18 '21 at 10:38
  • @Migo101 you need to use``axios.get()`` not ``axios.post()``. You don't have a ``app.post('/', (req, res) => { ... });`` POST route handler. That's why you also get 404. – M. Çağlar TUFAN May 18 '21 at 10:40
0

You're not sending CORS headers on your responses, so the requests are denied. This can be easily solved by:

  1. Run npm i cors
  2. Change your code to
const express = require('express')
const cors = require('cors');

const app = express()
const port = 5000;

app.use(cors());

// all the other stuff
Ron B.
  • 1,502
  • 2
  • 7
0

Install CORS npm package to configure your express HTTP server cors.

npm install cors

Then import CORS package in your express application file like that:

const express = require('express')
const cors = require('cors')

app.use(cors())

const app = express()
const port = 5000;

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Then in your request code, you should to request with GET method. You are using axios.post() which does POST request. And that will response you with 404 because you don't have app.post('/') route handler in your application. So the code should look like this:

const express = require('express')
const cors = require('cors')

app.use(cors())

const app = express()
const port = 5000;

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.post('/', (req, res) => {
  res.send(Hello ${req.body.firstName} ${req.body.lastName}!`)`;
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
M. Çağlar TUFAN
  • 626
  • 1
  • 7
  • 21
0

This error basically occurs because of a security mechanism that browsers implement called the same-origin policy. It prevents any cross-domain communication which may lead to cyber attacks like cross-site request forgery.

While we develop backend APIs for our frontend apps, we have to enable Cross-Origin Resource Sharing (CORS) in our backend server. To do that there are several libraries, the most common one is Cors package. Install it and use it in your server app as follows-

const express = require('express');
const app = express();
const port = 5000;

app.use(cors());

app.get('/', (req, res) => {
  res.send('Hello World!')
})