簡體   English   中英

反應節點快遞應用程序 - Heroku CORS 錯誤

[英]React node express app - Heroku CORS error

我在 Heroku 上設置了一個快速項目,並在 vercel 上設置了一個反應前端。 當我從前端發出請求時,我收到以下錯誤:

CORS 策略阻止了從源“https://helpr-front.vercel.app”獲取“https://helpr-dev.herokuapp.com/users/register”的訪問權限:對預檢請求的響應不通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”header。 如果不透明的響應滿足您的需求,請將請求的模式設置為“no-cors”以獲取禁用 CORS 的資源。

我在 Express 應用程序上實現了 CORS:

const cors = require('cors')
app.use(cors())

而且我也嘗試過給它傳遞一個配置,比如:

const whitelist = ['http://localhost:3000', 'https://helpr-front.vercel.app/']
const corsOptions = {
  origin: function (origin, callback) {
    if (!origin || whitelist.indexOf(origin) !== -1) callback(null, true)
    else callback(new Error('Not allowed by CORS'))
  },
  credentials: true,
}

app.use(cors(corsOptions))

這是請求在 React 應用程序中的樣子:

const submitRegisterForm = async e => {
        e.preventDefault()

            const response = await fetch(`${serverUrl}/users/register`, {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: name,
                    email: email,
                    password: password,
                    accountType: accountType
                })
            })

            const data = await response.json()
        
    }

我試過刪除mode: 'cors'部分,但它沒有任何區別。

有人可以告訴我我在這里缺少什么嗎?

前端應用托管在這里: https://helpr-front.vercel.app/后端應用托管在這里: https://helpr-dev.herokuapp.com/

前端完整代碼可以在這里找到: https://github.com/coccagerman/helpr-front后端完整代碼可以在這里找到: https://github.com/coccagerman/helpr-back

謝謝!

https://helpr-front.vercel.app/不是Web 來源 在原始白名單中刪除該斜杠:

const whitelist = ['http://localhost:3000', 'https://helpr-front.vercel.app']

您還需要明確允許Content-Type請求 header, 因為您使用application/json作為其值。

const whitelist = ['http://localhost:3000', 'https://helpr-front.vercel.app']
const corsOptions = {
  origin: function (origin, callback) {
    if (!origin || whitelist.indexOf(origin) !== -1) callback(null, true)
    else callback(new Error('Not allowed by CORS'))
  },
  credentials: true,
  allowedHeaders: ["Content-Type"],
}

app.use(cors(corsOptions))

所以這主要是由與 mongoDb 地圖集的連接問題引起的。 首先,Heroku IP 地址未在數據庫網絡連接上列入白名單。 像這里提到的那樣修復它: Connecting Heroku App to Atlas MongoDB Cloud service

然后我在使用的 mongo atlas 連接 URI 上出現錯誤。

最后,似乎有必要在我提出的每個請求上添加mode: 'cors',配置。

在 express 上,不需要 cors 配置。 我只是使用app.use(cors())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM