简体   繁体   English

与React,Axios,Express一起使用时如何解决CORS错误?

[英]How to solve CORS error when using with React, Axios, Express?

I am making simple twitter login using passport js, but when calling twitter route, I get CORS error.我正在使用护照 js 进行简单的 twitter 登录,但是在调用 twitter 路由时,出现 CORS 错误。

server.js服务器.js

const express = require("express");
const session = require("express-session");
const dotenv = require("dotenv");
const userLoginRoutes = require("./routes/userLoginRoute");
const cors = require("cors");
const app = express();

app.use(cors());
app.use(function (req, res, next) {
  res.header(
    "Access-Control-Allow-Origin",
    "*"
  ); // update to match the domain you will make the request from
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});
app.get("/api/auth/twitter", passport.authenticate("twitter"));

action dispatching here动作调度在这里

import {
  USER__LOGIN,
  USER__LOGIN__FAILURE,
  USER__LOGIN__SUCCESS,
} from "../constants/loginconstants";

const axios = require("axios");

// login action
export const userLoginAction = () => async (dispatch) => {
  try {
    dispatch({
      type: USER__LOGIN,
    });
    const config = {
      header: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin" : "*"
      },
    };
    const { data } = await axios.get(`/api/auth/twitter`, config);
    dispatch({
      type: USER__LOGIN__SUCCESS,
      payload: data,
    });
  } catch (error) {
    dispatch({
      type: USER__LOGIN__FAILURE,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

in package.json in client,在 package.json 客户端中,

  "proxy": "http://127.0.0.1:3001",

Also I cannot see Access-Control-Allow-Origin in the.network tab, see here,此外,我在 .network 选项卡中看不到 Access-Control-Allow-Origin,请参见此处, 在此处输入图像描述

Is there anything wrong while setting the Access-Control-Allow-Origin ?设置Access-Control-Allow-Origin时有什么问题吗?

I cannot figure out, where am I getting wrong.我不知道,我哪里错了。 I have used cors, and even manually set the origin to *.我用过cors,甚至手动设置原点为*。

Cors error that i am getting,我得到的 Cors 错误, 错误

Add CORS in node.js express API在 node.js express API 中添加 CORS

In order to add CORS to our API, there are different ways by which you can accomplish this.为了将 CORS 添加到我们的 API,您可以通过不同的方式来完成此操作。 It could be by manually writing an express middleware and telling your server which requests to allow and from which origin or by using CORS npm library which has done much of the heavy lifting for us.可以通过手动编写一个快速中间件并告诉您的服务器允许哪些请求以及来自哪个来源,或者通过使用 CORS npm 库,它为我们完成了很多繁重的工作。

In this article, we will be using cors npm library which can be easily passed as an express middleware.在本文中,我们将使用 cors npm 库,它可以作为快速中间件轻松传递。 First of all, install calls on your server-side app by running the command.首先,通过运行命令在您的服务器端应用程序上安装调用。

npm install cors

Then you can add it as a middleware like this然后你可以像这样将它添加为中间件

const express = require("express");
const cors = require("cors");
const app = express();
//use cors as middleware
app.use(cors())

The above code is the default way of adding CORS as an express middleware but what if you want to specify the origin of your client app?上面的代码是将 CORS 添加为快速中间件的默认方式,但是如果您想指定客户端应用程序的来源怎么办? Well let's learn different ways to configure CORS in node js app.好吧,让我们学习在 node js 应用程序中配置 CORS 的不同方法。

Allow requests from all domains.允许来自所有域的请求。

To allow our node.js server to handle all requests from all domains in our application, we will have to configure cors and pass it an origin key with a wildcard value shown below.为了让我们的 node.js 服务器能够处理来自应用程序中所有域的所有请求,我们必须配置 cors 并向其传递一个带有通配符值的原始键,如下所示。

//other imports
app.use(
  cors({
    origin: “*”,
  })
);

The issue with the above configuration is that, you client-side application CAN NOT share cookies nor authentication headers even if the credentials key is passed with a value of true as shown below.上述配置的问题是,您的客户端应用程序不能共享 cookie 或身份验证标头,即使凭证密钥以 true 值传递,如下所示。

Note: The origin key in cors option CORS take different option types such string, boolean, function or an array.注意: cors 选项 CORS 中的 origin 键采用不同的选项类型,例如字符串、布尔值、函数或数组。

//other imports
app.use(
  cors({
    origin: “*”,
    credentials: true
  })
)

Another key important thing to note is that, whenever you are not passing withCredentials: true in your client request API, DO NOT pass credentials: true in your cors config server-side most especially if you are using wildcard (*) as the origin of your request header.另一个需要注意的重要事项是,当您没有在客户端请求 API 中传递withCredentials: true时,请勿在您的 cors 配置服务器端传递credentials: true尤其是当您使用通配符 (*) 作为您的请求标头。

Tell CORS to set the origin to the request origin告诉 CORS 将源设置为请求源

In order to configure CORS to set the origin to the request origin, simply pass a boolean true value to origin key as shown below;为了配置 CORS 以将源设置为请求源,只需将布尔值 true 值传递给源键,如下所示;

//other imports
app.use(
  cors({
    origin: true,
    credentials: true
  })
)

Although this will allow your client app to share cookies and auth headers with your server unlike using wildcard but this also is not well secure enough unless it's an open API.尽管与使用通配符不同,这将允许您的客户端应用程序与您的服务器共享 cookie 和 auth 标头,但这也不够安全,除非它是一个开放的 API。

Configure CORS to set the origin to a single domain

In order to configure cors to set the origin to a single domain, simply pass a string true value to origin key as shown below;为了配置 cors 将 origin 设置为单个域,只需将字符串 true 值传递给 origin 键,如下所示;

//other imports
app.use(
  cors({
    origin: “http://localhost:3000”,
    credentials: true
  })
)

The above configuration will allow your client app to accept requests only from http://localhost:3000 and share cookies and auth headers with your server.上述配置将允许您的客户端应用程序仅接受来自 http://localhost:3000 的请求,并与您的服务器共享 cookie 和 auth 标头。 This configuration is tightly secure but not robust enough.这种配置非常安全,但不够稳健。

Configure CORS to set the origin to multiple whitelisted domains配置 CORS 以将源设置为多个列入白名单的域

What if you have microservice applications hosted on different domains or you want different domains to make requests to your API?如果您将微服务应用程序托管在不同的域上,或者您希望不同的域向您的 API 发出请求,该怎么办? Well, you can simply configure cors passing by an array of allowed domains to the origin key as shown below;好吧,您可以简单地配置通过一组允许域传递给源键的 cors,如下所示;

//other imports
const allowedDomains = [“http://localhost:3000”, “http://localhost:4000”, “http://localhost:6000”]
app.use(
  cors({
    origin: allowedDomains,
    credentials: true
  })
)

The above configuration will allow your client app to accept requests from any of the above domains listed in the array and share cookies and auth headers with your server.上述配置将允许您的客户端应用程序接受来自阵列中列出的上述任何域的请求,并与您的服务器共享 cookie 和 auth 标头。

CORS middleware can be passed as a global middleware and on a single route but all the methods shown above are ways to globally configure your CORS within your app. CORS 中间件可以作为全局中间件并在单个路由上传递,但上面显示的所有方法都是在应用程序中全局配置 CORS 的方法。 Let's briefly see how we can pass CORS middleware on a single route.让我们简要看看如何在单个路由上传递 CORS 中间件。 Note that, all the ways described above can be used on your routes as well.请注意,上述所有方式也可以在您的路线上使用。

const allowedDomains = [“http://localhost:3000”, “http://localhost:4000”, “http://localhost:6000”]
app.get(“/api/posts”, 
  cors({
    origin: allowedDomains,
    credentials: true
  }), 
  (req, res) =>{
    res.send(“everything still works”)
})

NOTE: Whenever you're a making a client-side request with the option of withCredentials: true , ensure your CORS configuration is passed credentials: true as an option as well else cookies won't be shared.注意:每当您使用withCredentials: true选项发出客户端请求时,请确保您的 CORS 配置已通过credentials: true作为选项,否则不会共享 cookie。 Another key important;另一个重要的关键; thing to note is that, whenever you're using wildcard () as the origin, DO NOT use withCredentials: true * on the client and credentials: true on server.需要注意的是,每当您使用通配符 () 作为来源时,请勿在客户端上使用withCredentials: true * 和在服务器上使用凭据:true。

Check your URL检查你的 URL

For google cloud functions users对于谷歌云功能用户

If there is a typo in your URL endpoint such as on functions name, the browser will actually show CORS error.如果您的 URL 端点有拼写错误,例如函数名称,浏览器实际上会显示 CORS 错误。

I had a typo in my URL and wasted a loooot of time searching CORS fixes.我的 URL 中有错字,浪费了很多时间搜索 CORS 修复程序。

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

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