使用CORS:No' Access-Control-Allow-Origin'标头出现在请求的资源上

时间:2018-03-22 07:50:18

标签: javascript cors

在制作中,我发布到ExpressJS服务器以使用Stripe API进行付款。出于某种原因,虽然我正在使用CORS并将原始URL列入白名单,但是我仍然会收到同样的错误:No 'Access-Control-Allow-Origin' header is present on the requested resource

这是我的server.js文件,我在其中定义了cors:

const cors = require('cors');
const bodyParser = require('body-parser');

const CORS_WHITELIST = require('./constants/frontend');

const corsOptions = {
  origin: (origin, callback) =>
    (CORS_WHITELIST.indexOf(origin) !== -1)
      ? callback(null, true)
      : callback(new Error('Not allowed by CORS'))
};

const configureServer = app => {
  app.use(cors(corsOptions));

  app.use(bodyParser.json());
};

module.exports = configureServer;

index.js文件是使用configureServer函数的地方:

const express = require('express');

const SERVER_CONFIGS = require('./constants/server');

const configureServer = require('./server');
const configureRoutes = require('./routes');

const app = express();

configureServer(app);
configureRoutes(app);

app.listen(SERVER_CONFIGS.PORT, error => {
  if (error) throw error;
  console.log('Server running on port: ' + SERVER_CONFIGS.PORT);
});

这里是frontend.js文件,其中定义了白名单URL:

const FRONTEND_DEV_URLS = [ 'http://localhost:5000' ];

const FRONTEND_PROD_URLS = [
  'https://www.example.com',
  'https://example.com'
];

module.exports = process.env.NODE_ENV === 'production'
  ? FRONTEND_PROD_URLS
  : FRONTEND_DEV_URLS;

我似乎无法调试此问题。特别是考虑到它只发生在生产中。

0 个答案:

没有答案
相关问题