mis*_*kis 8 javascript heroku node.js express
我在 Heroku 上遇到 CORS 问题。
这是我在服务器上的代码
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
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(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use('/films', filmRoutes)
app.use('/users', userRoutes)
export default app;
Run Code Online (Sandbox Code Playgroud)
这是我的帖子请求
CheckLogin = () => {
const data = {
name: this.state.formInput.login.value,
password: this.state.formInput.password.value
}
axios.post('https://whispering-shore-72195.herokuapp.com/users/login', data)
.then(response=>{
console.log(response);
const expirationDate = new Date(new Date().getTime() + response.data.expiresIn * 1000)
localStorage.setItem('token', response.data.token)
localStorage.setItem('expirationDate', expirationDate)
this.context.loginHandler()
})
.catch(err=>{
console.log(err)
})
console.log(data);
}
Run Code Online (Sandbox Code Playgroud)
这是错误
从源“ https://mighty-citadel-71298.herokuapp.com ”访问“ https://whispering-shore-72195.herokuapp.com/users/login ”的XMLHttpRequest已被 CORS 政策阻止:无“访问” -Control-Allow-Origin' 标头存在于请求的资源上。
我尝试了很多方法,但一无所获……知道吗?
小智 9
您需要确定这确实是CORS问题还是您的 API 代码已损坏。
如果是CORS问题,请像上面建议的那样在后端代码中处理CORScors或使用该包。
然而,很多时候,问题是你的代码被破坏了,而你只是不知道。例如,就我而言,我没有添加nodemon依赖项,并且我的start脚本依赖于nodemonHeroku 找不到的依赖项。因此,您的代码可能在开发中运行良好,但在生产中却崩溃了。
以下是如何找到 Heroku 中代码的哪一部分被破坏的方法:
503 Service Unavailable如下所示,则再次表明您的代码已损坏。


您已经在https://whispering-shore-72195.herokuapp.com 上从 origin https://mighty-citadel-71298.herokuapp.com跨域了
您可以尝试将npm 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;
Run Code Online (Sandbox Code Playgroud)
我已经测试了您的客户端调用登录到您的服务器,https并且它在没有 CORS 问题的情况下工作。也许你已经成功修复了它。
我在StackBlitz上尝试过 simple并且它工作成功。
您可以尝试登录https://js-53876623.stackblitz.io/检查时并查看网络选项卡,看到OPTIONS (200 status)和POST (404 not found)(因为我不知道在你的数据库中的任何用户)
我已经在我的本地尝试过你的代码,也许你没有测试和处理所有错误,不幸的是它让你的应用程序崩溃。
我已经运行了您的代码并注意到问题可能是jsonwebtoken错误:
错误:secretOrPrivateKey 必须有一个值
请尝试使用process.env.JWT_KEY || 'Require key here!!!',,并JWT_KEY在您的环境中设置您的或||用作服务器上的默认密钥。
也许它会解决你的问题。
我对您的代码有一些建议:
User.findOne()代替User.find()app.use(cors());jsonwebtoken在服务器上运行时应该使用异步而不是同步。| 归档时间: |
|
| 查看次数: |
34879 次 |
| 最近记录: |