HEROKU上的CORS问题 [英] CORS problems on HEROKU

查看:28
本文介绍了HEROKU上的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Heroku上使用CORS时遇到问题.

I have problem with CORS on Heroku.

这是我在服务器上的代码

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;

这是我的发帖请求

  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);
  }

这是错误

在以下位置访问XMLHttpRequest' https://whispering-shore-72195.herokuapp.com/users/login'从起源" https://mighty-citadel-71298.herokuapp.com 已被CORS阻止策略:请求的资源.

Access to XMLHttpRequest at 'https://whispering-shore-72195.herokuapp.com/users/login' from origin 'https://mighty-citadel-71298.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我尝试了很多方法,却一无所获...知道吗?

I tried a lot of methods and nothing... any idea?

推荐答案

您已经跨过https://whispering-shore-72195.herokuapp.com 来自来源 https://mighty-citadel-71298.herokuapp.com

您可以尝试 npm cors软件包作为中间件,而不是自定义的中间件. CORS 软件包允许您进行多个配置,并且非常易于使用.

You can try npm cors package as middleware instead of your custom middleware. CORS package allows you multiple configure and it's very easy to use.

简单用法(启用所有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;

我已经测试了您的客户端呼叫从 https 登录到服务器的过程,并且可以正常使用而没有CORS问题.也许您已经成功修复了它.

I've test your client call login to your server from https and it's working without CORS problem. Maybe you had fixed it successfully.

我已经尝试过在 StackBlitz 上进行简单操作,并且可以正常工作成功.

I've tried with simple on StackBlitz and it's working successfully.

您可以尝试登录 https://js-53876623.stackblitz.io/并查看检查时查看网络"选项卡,并查看 OPTIONS(200个状态) POST(未找到404)(因为我在您的数据库中不认识任何用户)

You can try login https://js-53876623.stackblitz.io/ and view network tab when inspecting and see OPTIONS (200 status) and POST (404 not found) (because I don't know any user in your database)

我已经在本地尝试过您的代码,也许您没有测试并处理所有错误,不幸的是,这使您的应用程序崩溃了.

I've tried your code on my local, maybe you hadn't tested and handled all error, it makes your app crash unfortunately.

我已经运行了您的代码,发现问题可能是 jsonwebtoken 错误:

I've run your code and noticed the problem maybe jsonwebtoken error:

错误:secretOrPrivateKey必须具有一个值

Error: secretOrPrivateKey must have a value

请尝试使用 process.env.JWT_KEY ||在这里需要密钥!!",,然后在您的环境中设置您的 JWT_KEY 或在服务器上使用 || 作为默认密钥.

Please tried with process.env.JWT_KEY || 'Require key here!!!',, and set your JWT_KEY on your environment or use || as default key on server.

也许可以解决您的问题.

Maybe it will fix your problem.

对于您的代码,我有一些建议:

I have some recommends for your code:

  • 请使用 User.findOne()而不是 User.find()
  • 请使用 app.use(cors());
  • 在服务器上运行时,
  • jsonwebtoken 应该使用异步而不是同步".
  • Please use User.findOne() instead of User.find()
  • Please use app.use(cors());
  • jsonwebtoken should use Asynchronous instead of Sync when run on server.

这篇关于HEROKU上的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆