【发布时间】:2020-10-05 20:22:57
【问题描述】:
几天以来,我一直在尝试让我的应用在 Heroku 上运行,但我遇到了 CORS 问题。 我阅读了软件包 cors 文档,我认为我做得对,但你可以在这里看到我的后端:https://github.com/Karlus44/orientation-back (我会粘贴相关代码) 你也可以在这里找到我的前端:https://github.com/Karlus44/orientation-front 并看到当您访问我的应用程序(此处:https://orientation-front.herokuapp.com/)时,您遇到了一些 CORS 错误。 谢谢你的帮助 这是我服务器中的代码:
const express = require('express');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const multer = require('multer');
//many declarations
const app = express();
app.use(express.urlencoded({extended: false}));
app.use(express.json());
var corsOptions = {
origin: 'https://orientation-front.herokuapp.com',
methods: 'GET,POST',
allowedHeaders: 'Content-Type',
optionsSuccessStatus: 200
}
app.options('*', cors(corsOptions));
app.get('/',cors(corsOptions), (req,res)=>{
return db('utilisateurs').count('id')
.then(data => res.json(data));
})
//example of request
app.post('/signin', cors(corsOptions), (req,res) => {signin.handleSignin(req,res, db, bcrypt)})
【问题讨论】:
-
您的 cors 包是否添加到“devDependencies”中,请添加到“dependencies”中?
-
嗯,它已经在我的依赖项中了。现在我也将它添加到我的 devDependencies 中,但没有任何改变
-
你应该使用 app.use(cors());而不是 app.options('*', cors(corsOptions));.
-
我试过你的修改,但仍然遇到同样的问题
-
你应该使用 app.use(cors());在您的 sever.js 文件中的第 5 行。