0

I want to make a post call to a local express server running on port 8001 with axios in my react code like below:

axios.post('http://localhost:8001/enterInfo',{headers: { 'crossDomain': true }}, payload)
        .then((response) => {
            this.setState({
                saved:true
            })
        })

My express server is listening on port 8001. and i have written a post method in my express server:

app.post('/postUrl', (req, res) => {
console.log(req.body);
res.send('111');
});

but when i make the call from the react ui, it is giving this error:

XMLHttpRequest cannot load http://localhost:8001/enterInfo. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

sideshowbarker
  • 72,859
  • 23
  • 167
  • 174
Probosckie
  • 1,293
  • 3
  • 20
  • 35

1 Answers1

5

You have to enable cross-origin resource sharing on your server.

Check this package :

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.post('/postUrl', (req, res) => {
   console.log(req.body);
   res.send('111');
});
Valentin Duboscq
  • 940
  • 9
  • 19