简体   繁体   English

NodeJS Express 和 ReactJS 的 CORS 问题

[英]CORS problem with NodeJS Express and ReactJS

I have some CORS problem with NodeJS Express and ReactJS.我对 NodeJS Express 和 ReactJS 有一些 CORS 问题。 Please help me.请帮我。

Now, I have both frontend( http://locahost:3000 ) and backend( http://locahost:4000 ) using different PORT .现在,我有两个前端( http://locahost:3000 )和后端( http://locahost:4000 )使用不同的PORT The frontend is using 3000 port with ReactJS and the Backend is using 4000 port with NodeJS Express.前端使用 ReactJS 的 3000 端口,后端使用 NodeJS Express 的 4000 端口。

Frontend API call source code前端API调用源码

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

Backend CORS setting source code后端CORS设置源码

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.但它仍然有与吹错误消息相同的问题,即使我设置了 CORS 设置。

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. 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请求的资源。

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.在您的客户端请求上使用Content-Type: application/json会使您的跨源请求成为需要预飞行的请求,并且客户端将向您服务器上的该路由发送一个 OPTIONS 请求,本质上是询问您的服务器是否允许对该路线进行跨源呼叫。 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:为了使这种类型的请求在浏览器中成功,您需要一个用于返回 200 状态的 OPTIONS 动词的处理程序,如下所示:

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.但是,更简单的解决方案可能只是从您的客户端请求中删除自定义 Content-Type header。 The Content-Type header specifies the type of content you are SENDING with the request, not the type of content you are expecting back. Content-Type header 指定您通过请求发送的内容类型,而不是您期望返回的内容类型。 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. 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:在没有预检的情况下唯一允许的Content-Type header 值是:

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.您会注意到application/json未列出,因此使用该内容类型会强制浏览器执行您的服务器未处理的预飞行。

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.如果这不起作用,那么您应该通过查看浏览器中的 Chrome 调试器网络选项卡来进一步诊断,并准确查看浏览器运行 Ajax 调用时发生的情况。 Chances are you will see an OPTIONS request that comes back as a 404 or some other non-200 status.您可能会看到一个 OPTIONS 请求以 404 或其他一些非 200 状态返回。 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.如果是这种情况,那么您需要在您的服务器中添加一个特定的 OPTIONS 处理程序,该处理程序为该路由返回 200 状态。 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.您有将设置 CORS 标头的中间件,但您在该路由中调用next() ,因此由于没有其他匹配的 OPTIONS 路由处理程序,它可能会落入 404 处理程序,因此浏览器认为 OPTIONS 请求失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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