使用cors包和设置Access-Control标头都没有运气

时间:2018-03-03 21:15:52

标签: node.js express cors http-status-code-400

好的,所以我遇到了Access-Control标头的问题。奇怪的是,它工作了一段时间,然后突然停止工作,没有我修改代码。我从本地运行的反应应用程序发送请求。我请求的服务器托管在heroku上,我收到的错误消息是:

" Access-Control-Allow-Origin"

不允许原点http://localhost:3000

此代码中是否存在导致此错误的错误?

var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var cors = require('cors');

var app = express();

app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Access-Token');
  next();
});

我抓住了请求:

Request URL:https://secret-server.herokuapp.com/levels/
Request Method:GET
Status Code:400 Bad Request
Remote Address:**.***.***.**:443
Referrer Policy:no-referrer-when-downgrade

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-GB,en-US;q=0.9,en;q=0.8
Connection:keep-alive
Host:secret-server.herokuapp.com
Origin:http://localhost:3000
Referer:http://localhost:3000/

1 个答案:

答案 0 :(得分:0)

您是否尝试过以这种方式设置cors选项:

var corsOptions = {
  origin: '*',
  optionsSuccessStatus: 200,
  methods: ['GET','PUT', 'POST', 'DELETE'],
  allowedHeaders: ['X-Access-Token'],
  preflightContinue: true
}

app.use(cors(corsOptions))