【发布时间】:2021-12-31 14:42:42
【问题描述】:
我在 Heroku 上设置了一个 express 项目,并在 vercel 上设置了一个反应前端。 当我从前端发出请求时,我收到以下错误:
CORS 政策已阻止从源“https://helpr-front.vercel.app”访问“https://helpr-dev.herokuapp.com/users/register”获取:响应预检请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“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
谢谢!
【问题讨论】:
-
您能确认您的应用程序运行正常吗?您可以通过查看日志或输入 heroku 控制台来完成此操作
-
我在部署时没有收到任何错误。如何检查它是否正在运行?
-
简单查看应用程序的日志,如果这对您没有帮助,您可能需要使用 bash 进入您的实例并手动运行应用程序(node app.js)以查看它是否运行正确
-
这些是我找到的日志:justpaste.it/91vti 我也手动运行了它,它似乎工作正常。
-
你试过简单的
corsOptions = { origin: 'https://helpr-front.vercel.app' }吗?
标签: javascript node.js express heroku cors