简单的CORS设置无法正常工作

时间:2018-03-14 23:29:32

标签: node.js express superagent

这是我的服务器代码:

import express from 'express';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';

const app = express();

// app.use(cors()); // Also tried this
app.use(cors({ credentials: true, origin: true }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/', (req, res) => res.json({ message: 'OK' }));

app.listen(3000);

以下是我的网站代码(由localhost:5000提供):

const response = await superagent.get('localhost:3000/')
  .withCredentials()
  .send();

但这被CORS阻止了:

  

错误:请求已终止   可能的原因:网络脱机,Access-Control-Allow-Origin不允许Origin,页面正在卸载等。

为什么?

我使用的是Firefox 58和Node.js 6.10。

1 个答案:

答案 0 :(得分:0)

我忘记了http://前缀:

const response = await superagent.get('http://localhost:3000/')
  .send();

一天......