CORS problem with NodeJS Express and ReactJS

ぐ巨炮叔叔 提交于 2021-02-17 07:11:13

问题


I have some CORS problem with NodeJS Express and ReactJS. Please help me.

Now, I have both frontend(http://locahost:3000) and backend(http://locahost:4000) using different PORT. The frontend is using 3000 port with ReactJS and the Backend is using 4000 port with NodeJS Express.

Frontend API call source code

axios.get("/tube/latestted",
    {
        headers: {
            "Content-Type": "application/json",
        },
    })
    .then(response => {
        console.log(response);
    });

Backend CORS setting source code

app.all('/*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');

  next();
});

or

var cors = require('cors');
app.use(cors());

But it still has the same problem as the blow error message, even though I set up CORS setup.

Access to XMLHttpRequest at 'http://localhost:4000/tube/latestted' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


回答1:


Using Content-Type: application/json on your client-side request makes your cross origin request into a request that needs pre-flight and the client will send an OPTIONS request to your that route on your server essentially asking your server if it's permissible to make a cross origin call to that route. For that type of request to succeed in a browser, you need a handler for the OPTIONS verb that returns a 200 status like this:

app.options("/tube/latestted", (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');        
    res.sendStatus(200);
});

But, a simpler solution is likely to just remove the custom Content-Type header from your client request. The Content-Type header specifies the type of content you are SENDING with the request, not the type of content you are expecting back. Since you are sending no data with the GET request, you do not need that header and it is that header that is making your Ajax call go from a Simple Request to a Pre-Flighted Request which requires the OPTIONS preflight.

The only Content-Type header values that are allowed without preflight are:

application/x-www-form-urlencoded
multipart/form-data
text/plain

You will notice that application/json is not listed so using that content-type is forcing the browser to do pre-flight which your server is not handling.

So, the first thing to try is to change the client request to this:

axios.get("/tube/latestted")
  .then(response => {
     console.log(response);
  }).catch(err => {
     console.log(err);
  });

If that doesn't work, then you should diagnose further by looking at the Chrome debugger Network tab in the browser and see exactly what is happening when the browser runs that Ajax call. Chances are you will see an OPTIONS request that comes back as a 404 or some other non-200 status. If that's the case, then you need to add a specific OPTIONS handler in your server that returns a 200 status for that route. You have middleware that will set the CORS headers, but you call next() in that route so since there is no other matching OPTIONS route handler, it will presumably fall through to a 404 handler and thus the browser thinks the OPTIONS request has failed.



来源:https://stackoverflow.com/questions/65153590/cors-problem-with-nodejs-express-and-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!