React节点快递应用程序-Heroku CORS错误



我在Heroku上设置了一个express项目,在vercel上设置了react前端。当我从前端发出请求时,我会收到以下错误:

在'获取的访问权限https://helpr-dev.herokuapp.com/users/register'来自原点'https://helpr-front.vercel.app'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在"access control Allow Origin"标头。如果不透明响应满足您的需求,请将请求的模式设置为"无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

谢谢!

所以这主要是由于与mongoDb图谱的连接出现问题引起的。首先,Heroku IP地址没有被列入数据库网络连接的白名单。修复了这里提到的问题:将Heroku应用程序连接到Atlas MongoDB云服务

然后我在我使用的mongo atlas连接URI上出现了一个错误。

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

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