繁体   English   中英

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

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

我正在使用护照 js 进行简单的 twitter 登录,但是在调用 twitter 路由时,出现 CORS 错误。

服务器.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"));

动作调度在这里

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

在 package.json 客户端中,

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

此外,我在 .network 选项卡中看不到 Access-Control-Allow-Origin,请参见此处, 在此处输入图像描述

设置Access-Control-Allow-Origin时有什么问题吗?

我不知道,我哪里错了。 我用过cors,甚至手动设置原点为*。

我得到的 Cors 错误, 错误

在 node.js express API 中添加 CORS

为了将 CORS 添加到我们的 API,您可以通过不同的方式来完成此操作。 可以通过手动编写一个快速中间件并告诉您的服务器允许哪些请求以及来自哪个来源,或者通过使用 CORS npm 库,它为我们完成了很多繁重的工作。

在本文中,我们将使用 cors npm 库,它可以作为快速中间件轻松传递。 首先,通过运行命令在您的服务器端应用程序上安装调用。

npm install cors

然后你可以像这样将它添加为中间件

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

上面的代码是将 CORS 添加为快速中间件的默认方式,但是如果您想指定客户端应用程序的来源怎么办? 好吧,让我们学习在 node js 应用程序中配置 CORS 的不同方法。

允许来自所有域的请求。

为了让我们的 node.js 服务器能够处理来自应用程序中所有域的所有请求,我们必须配置 cors 并向其传递一个带有通配符值的原始键,如下所示。

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

上述配置的问题是,您的客户端应用程序不能共享 cookie 或身份验证标头,即使凭证密钥以 true 值传递,如下所示。

注意: cors 选项 CORS 中的 origin 键采用不同的选项类型,例如字符串、布尔值、函数或数组。

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

另一个需要注意的重要事项是,当您没有在客户端请求 API 中传递withCredentials: true时,请勿在您的 cors 配置服务器端传递credentials: true尤其是当您使用通配符 (*) 作为您的请求标头。

告诉 CORS 将源设置为请求源

为了配置 CORS 以将源设置为请求源,只需将布尔值 true 值传递给源键,如下所示;

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

尽管与使用通配符不同,这将允许您的客户端应用程序与您的服务器共享 cookie 和 auth 标头,但这也不够安全,除非它是一个开放的 API。

Configure CORS to set the origin to a single domain

为了配置 cors 将 origin 设置为单个域,只需将字符串 true 值传递给 origin 键,如下所示;

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

上述配置将允许您的客户端应用程序仅接受来自 http://localhost:3000 的请求,并与您的服务器共享 cookie 和 auth 标头。 这种配置非常安全,但不够稳健。

配置 CORS 以将源设置为多个列入白名单的域

如果您将微服务应用程序托管在不同的域上,或者您希望不同的域向您的 API 发出请求,该怎么办? 好吧,您可以简单地配置通过一组允许域传递给源键的 cors,如下所示;

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

上述配置将允许您的客户端应用程序接受来自阵列中列出的上述任何域的请求,并与您的服务器共享 cookie 和 auth 标头。

CORS 中间件可以作为全局中间件并在单个路由上传递,但上面显示的所有方法都是在应用程序中全局配置 CORS 的方法。 让我们简要看看如何在单个路由上传递 CORS 中间件。 请注意,上述所有方式也可以在您的路线上使用。

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

注意:每当您使用withCredentials: true选项发出客户端请求时,请确保您的 CORS 配置已通过credentials: true作为选项,否则不会共享 cookie。 另一个重要的关键; 需要注意的是,每当您使用通配符 () 作为来源时,请勿在客户端上使用withCredentials: true * 和在服务器上使用凭据:true。

检查你的 URL

对于谷歌云功能用户

如果您的 URL 端点有拼写错误,例如函数名称,浏览器实际上会显示 CORS 错误。

我的 URL 中有错字,浪费了很多时间搜索 CORS 修复程序。

暂无
暂无

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

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