为什么我不能从 localhost 客户端连接到 localhost 服务器(cors 错误)?

Why can't I connect to localhost server from localhost client (cors error)?

我在端口 4200 (http://localhost:4200) 上有一个本地 (Angular) 客户端 运行,在端口 5000 (http://localhost) 上有一个本地(快速)服务器:5000)。每当我尝试连接到我的服务器时,我都会收到此消息。

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NU7H' from origin 
'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是启动本地服务器的代码

@injectable()
export default class App {
  app: express.Application;

  constructor() {
    this.app = express();
    this.config();
    this.bindRoutes();
  }

  // Middlewares config
  private config(): void {
    this.app.use(cors());
    this.app.use(express.json());
    this.app.use(express.urlencoded({ extended: true }));
  }

  bindRoutes(): void {
    this.app.use('/', router);
  }
}

这是我设置套接字的代码

private _ioServer: SocketIO.Server;

initSocket(server: http.Server) {
    this._ioServer = new SocketIO.Server(server);

    this.connectChat(); // Chat namespace
    this.connectStream(); // Game board streaming namespace
}

我尝试使用 Postman,一切正常。

谢谢!

任何恶意网站都可以利用您存储在名为 Cross-site request forgery

的系统中的 cookie

任何浏览器都会试图阻止您进行这些攻击,因此它们会禁用 CORS。

Shorthand 修复 [不推荐] : 有很多插件可以用于本地测试,在浏览器上禁用这些检查。

正确修复: 当响应从服务器 return 返回时,使用 Express 中间件在您的 header 中应用 Access-Control-Allow-Origin: *

要点是,当浏览器向您的服务器发送请求时,它会将 Origin: http://localhost:3000 附加到 header。响应来自浏览器的这个请求,服务器应该 return a Access-Control-Allow-Origin header 来指定哪些来源可以访问服务器的资源。

你可以在这里严格 return Access-Control-Allow-Origin: http://localhost:4200 或者发送 Access-Control-Allow-Origin: *.

打开你的大门

这里是快速中间件的快速代码:

const express = require('express');
const request = require('request');

const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/jokes/random', (req, res) => {
  request(
    { url: 'https://joke-api-strict-cors.appspot.com/jokes/random' },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }

      res.json(JSON.parse(body));
    }
  )
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));

来源: https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9

P.S, this 是一本了解 CORS 的好书。