簡體   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