简体   繁体   中英

How can I fix this error with CORS in my nodejs application

I have following code in fe:

  getTasks = () => {
    axios.get("http://127.0.0.1:3000/api/getTasks", {
      withCredentials: true
    }).then(response => {
      console.log(response)
    })
  }

and this code in be:

var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', req.header('origin'));
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Credentials: true");
  next();
});

when the user logs in and requests getTasks(), I am getting this error:

Access to XMLHttpRequest at 'http://127.0.0.1:3000/api/getTasks' from origin 'http://localhost:3002' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

You can use npm CORS for this

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

app.use(cors())

// other stuff

It might be that you are not setting the property correctly.

Try: res.header("Access-Control-Allow-Credentials", "true");

You can learn more about CORS on the enable-cors website , and there are also sample CORS codes for ExpressJS.

In your ExpressJS app on node.js, do the following with your routes:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD"); // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Credentials", "true")
  next();
});

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM