【问题标题】:Why can't I connect to localhost server from localhost client (cors error)?为什么我无法从 localhost 客户端连接到 localhost 服务器(cors 错误)?
【发布时间】:2021-05-17 03:56:24
【问题描述】:

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

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 试过了,一切正常。

谢谢!

【问题讨论】:

    标签: express socket.io cors localhost localserver


    【解决方案1】:

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

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

    Shorthand Fix [不推荐]:您可以使用许多插件进行本地测试,从而禁用浏览器上的这些检查。

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

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

    您可以在这里严格回复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。

    【讨论】:

      猜你喜欢
      • 2011-05-14
      • 2019-10-05
      • 2014-05-04
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多