NodeJS Express和ReactJS的CORS问题 [英] CORS problem with NodeJS Express and ReactJS

查看:87
本文介绍了NodeJS Express和ReactJS的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对NodeJS Express和ReactJS有一些CORS问题.请帮助我.

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

现在,我同时使用不同的 PORT .前端在ReactJS上使用3000端口,而后端在NodeJS Express上使用4000端口.

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.

前端API调用源代码

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

后端CORS设置源代码

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();
});

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

但是,即使我设置了CORS设置,它仍然具有与打击错误消息相同的问题.

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

CORS策略已阻止从源"http://localhost:3000"访问"http://localhost:4000/tube/latestted"处的XMLHttpRequest:没有"Access-Control-Allow-Origin"标头出现在请求的资源上.

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.

推荐答案

在客户端请求上使用 Content-Type:application/json 会使您的跨源请求变成需要预先航班,客户将向您的服务器上的该路线发送OPTIONS请求,本质上是询问您的服务器是否可以对该路线进行跨源调用.为了使这种类型的请求在浏览器中成功执行,您需要一个OPTIONS动词的处理程序,该处理程序返回200状态,如下所示:

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);
});

但是,一个更简单的解决方案可能只是从客户请求中删除自定义Content-Type标头. Content-Type 标头指定要与请求一起发送的内容的类型,而不是期望返回的内容的类型.由于没有使用GET请求发送任何数据,因此不需要该标头,并且正是该标头使您的Ajax调用从

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.

在没有预检的情况下,唯一的 Content-Type 标头值是:

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

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

您会注意到未列出 application/json ,因此使用该内容类型将迫使浏览器进行服务器未处理的预检.

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);
  });

如果这不起作用,那么您应该通过查看浏览器中的Chrome调试器的网络"选项卡进一步诊断,并确切了解浏览器运行该Ajax调用时正在发生的情况.您很可能会看到以404或其他非200状态返回的OPTIONS请求.如果是这种情况,则需要在服务器中添加一个特定的OPTIONS处理程序,该处理程序将为该路由返回200状态.您有可以设置CORS标头的中间件,但是在该路由中调用了 next(),因此,由于没有其他匹配的OPTIONS路由处理程序,因此大概会落入404处理程序,从而使浏览器认为OPTIONS请求失败.

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.

这篇关于NodeJS Express和ReactJS的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆