您已跨源域https://whispering-shore-72195.herokuapp.com https://whispering-shore-72195.herokuapp.com从原点https://mighty-citadel-71298.herokuapp.com https://mighty-citadel-71298.herokuapp.com
你可以试试npm cors 包 https://www.npmjs.com/package/cors作为中间件而不是您的自定义中间件。CORS
包允许您进行多种配置,并且非常易于使用。
简单使用(启用所有 CORS 请求)
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
require('dotenv').config()
import filmRoutes from './api/routes/films'
import userRoutes from './api/routes/users'
const app = express()
const DBNAME = process.env.DB_USER
const DBPASSWORD = process.env.DB_PASS
mongoose.connect(`mongodb://${DBNAME}:${DBPASSWORD}@ds157422.mlab.com:57422/filmbase`, {useNewUrlParser: true})
/*app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});*/
app.use(cors()); // <---- use cors middleware
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use('/films', filmRoutes)
app.use('/users', userRoutes)
export default app;
Edit:
我已经测试了您的客户端呼叫登录到您的服务器https
并且它的工作没有 CORS 问题。也许你已经成功修复了它。
我尝试过简单的堆栈闪电战 https://stackblitz.com/edit/js-53876623?file=index.js并且它运行成功。
您可以尝试登录https://js-53876623.stackblitz.io/ https://js-53876623.stackblitz.io/并在检查时查看网络选项卡并查看OPTIONS (200 status)
and POST (404 not found)
(因为我不认识你数据库中的任何用户)
编辑 2018 年 12 月 22 日 - 晚上 7:18
我已经在本地尝试了您的代码,也许您没有测试并处理所有错误,不幸的是它使您的应用程序崩溃。
我已经运行了你的代码并注意到了这个问题jsonwebtoken
error:
错误:secretOrPrivateKey 必须有一个值
请尝试使用process.env.JWT_KEY || 'Require key here!!!',
,并设置你的JWT_KEY
根据您的环境或使用情况||
作为服务器上的默认密钥。
也许它会解决你的问题。
推荐:
我对您的代码有一些建议:
- 请用
User.findOne()
代替User.find()
- 请用
app.use(cors());
-
jsonwebtoken
应该使用异步而不是在服务器上运行时同步。