518651 2023-11-16 19:26 采纳率: 40%
浏览 67
已结题

NEXT.JS 跨域请求

运行环境:Next.JS + Windows 本地开发测试
问题描述:在路由:\Matchmaking\Room[roomid] 下我有一个连接Room服务的操作:

img

控制台报错:

img

我尝试使用配置Next.Config.Js 解决,但是失败了

img

我需要怎么解决问题:优先通过Next.JS 配置文件解决跨域请求,成功请求被阻止的地址,若不能则修改代码请求,最后则为Nginx配置修改

  • 写回答

17条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2023-11-16 19:27
    关注
    获得0.45元问题酬金

    引自强大而免费的微信小程序:皆我百晓生

    在Next.js中解决跨域请求问题可以尝试以下步骤:

    1. 在Next.js的配置文件next.config.js中添加CORS头信息。你已经尝试过这个步骤,请确保头信息设置正确。

      const nextConfig = {
      async headers() {
       return [
         {
           source: '/(.*)',
           headers: [
             {
               key: 'Access-Control-Allow-Origin',
               value: '*',
             },
           ],
         },
       ];
      },
      };
      module.exports = nextConfig;
      
    2. 如果上一步无效,你可以尝试修改代码中的请求,通过设置请求的modeno-cors禁用CORS。请注意,这可能会导致某些请求属性不可用。

      useEffect(() => {
      console.log("Connecting to Colyseus...");
      const clients = new Colyseus.Client('https://xxxx.cn:21151', { mode: 'no-cors' });
      console.log("Connected to Colyseus!");
      });
      
    3. 如果以上方法仍然不起作用,可能需要在Nginx中进行配置修改。请在你的Nginx配置文件中添加以下内容:

      location /matchmake/create/Game {
       if ($request_method = 'OPTIONS') {
           add_header 'Access-Control-Allow-Origin' '*';
           add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
           add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
           add_header 'Access-Control-Max-Age' 1728000;
           add_header 'Content-Type' 'text/plain charset=UTF-8';
           add_header 'Content-Length' 0;
           return 204;
       }
       if ($request_method 'POST') {
           add_header 'Access-Control-Allow-Origin' '*';
           add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
           add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
           add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
       }
       proxy_pass https://xxxx.cn:21151;
      }
      

    请确保将上述代码中的https://xxxx.cn:21151替换为你的实际接口地址。然后重新启动Nginx服务。

    希望这些步骤能帮助你解决跨域请求的问题。

    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 11月24日
  • 创建了问题 11月16日