React—— Next.js 配置 API 代理解决跨域问题

内容分享8小时前发布
0 0 0

什么是跨域?

当你的前端页面(比如
http://localhost:3000
)请求另一个域名的接口(比如
http://api.example.com
),浏览器会阻止这个请求,这就是跨域问题。


前端页面: http://localhost:3000
API接口:  http://api.example.com:8080
          ↑ 域名/端口不同,浏览器拒绝请求

解决方案:配置代理

代理的原理很简单:让前端请求自己的服务器,再由服务器转发给 API。


浏览器 → 前端服务器(代理) → API服务器
         同源,不跨域         服务器之间无跨域限制

Next.js 代理配置


next.config.js
中配置
rewrites


// next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'http://api.example.com:8080/api/:path*'
      }
    ]
  }
}

配置解释

配置项 含义

source
前端请求的路径,
:path*
表示匹配所有子路径

destination
实际转发的目标地址

效果

配置后,前端代码可以这样写:


// 请求 /api/users
// 实际会转发到 http://api.example.com:8080/api/users
fetch('/api/users')

多个代理配置

如果有多个不同的 API 服务,可以配置多条规则:


async rewrites() {
  return [
    {
      source: '/api/:path*',
      destination: 'http://api-server:8080/api/:path*'
    },
    {
      source: '/upload/:path*',
      destination: 'http://file-server:9000/upload/:path*'
    }
  ]
}

使用环境变量

不同环境(开发/测试/生产)可能有不同的 API 地址,可以用环境变量:


// next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: `${process.env.NEXT_PUBLIC_API_URL}/api/:path*`
      }
    ]
  }
}

# .env.development(开发环境)
NEXT_PUBLIC_API_URL=http://localhost:8080

# .env.production(生产环境)
NEXT_PUBLIC_API_URL=https://api.production.com

注意事项

仅开发环境生效
rewrites

next dev
时生效,生产环境需要 Nginx 等反向代理配合路径匹配顺序:多条规则按顺序匹配,第一个匹配的规则生效修改配置需重启:修改
next.config.js
后需要重启开发服务器

总结

步骤 操作
1
next.config.js
配置
rewrites
2 前端请求
/api/xxx
3 Next.js 自动转发到目标服务器
4 跨域问题解决

这种方式简单直接,无需后端配置 CORS,推荐在 Next.js 项目中使用。

© 版权声明

相关文章

暂无评论

none
暂无评论...