目录

解决React开发模式服务端Cors问题

目录

“解决React开发模式服务端Cors问题

启因

最近在做openai的后端代理服务,一个后台池账号池,缓冲前端过来的openaicompletion请求.

后端基本开发完成了,所以需要一个demo前端做测试及演示用,就用react做了一个简单的前端聊天程序,代码基本由GPT-4来生成,生成了多次,拼接了一下,由于我也没有写过react,所以还花了点时间选择拼接,因为CHATGPT也经常出些错误,懂的人一看就知道,不懂的人就要上当.

程序运行起来后,因为后端给前端的接口是一个websocket,启动后就报错: Access to XMLHttpRequest at 'http://localhost:3014/socket.io/?EIO=4&transport=polling&t=OSYSDmI' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

解决

查了一些资料,CORS问题其实需要在SERVER端解决,首先我的SERVER端用的是Nestjs,websocket用的是WebSocketGateway,定义如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@WebSocketGateway({
  cors: {
    origin: '*',
  },
  namespace: 'main',
})
export class WSGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  	...
  }

websockeet已经加了CORS了,应该不是这个问题,问题出在localhost:3000,这个是前端react用的web服务,报错也是这个3000,经过查询,开发模式启动react-scripts用的是webpack的开发服,根据官方文档:

新建一个scr/setupProxy.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const { createProxyMiddleware } = require("http-proxy-middleware");

module.exports = function (app) {
  app.use(
    "/",
    createProxyMiddleware({
      target: "http://localhost:3014", // Replace with the API server URL
      //   changeOrigin: true,
      ws: true,
      logger: console,
      //   pathRewrite: {
      //     "^/api": "", // Remove the '/api' prefix from the request URL
      //   },
    })
  );
};

target填入react要连接的目标服务器地址, ws设置成true