Next.js 13代理配置失效求助:如何实现跨端口API转发?
问题描述
在Next.js 13中配置代理时遇到问题,使用react-query 4.29.25从8000端口的后端获取数据。预期请求http://localhost:3000/api/v1/users时,Next.js会自动转发到http://127.0.0.1:8000/api/v1/users,但实际未生效。之前直接指定后端地址http://127.0.0.1:8000/api/v1可以正常请求,现在需要通过代理实现。
环境版本
- Next.js: 13
- React-query: 4.29.25
相关代码
next.config.js
/** @type {import('next').NextConfig} */ const nextConfig = { rewrites:{ source: "/api/:path*", destination: "http://127.0.0.1:8000/api/:path*", }, }; module.exports = nextConfig;
urls.ts
const BASE_BACKEND_V1 = window.location.origin + '/api/v1'; const urls = { base_backend: { users: `${BASE_BACKEND_V1}/users`, // other endpoints }, }; export default urls;
api.ts
import { useMutation, useQuery } from '@tanstack/react-query'; import urls from '../urls'; export const useUsersQuery(props = {}) => { const url = url.base_backend.users; const urlParamed = new URL(url); if (props.name) urlParamed.searchParams.append('name', props.name); return useQuery( ['useUsersQuery', ...Object.values(props)], async () => fetchWithAuth<Paginated<Excelsheet>>(urlParamed.href), { keepPreviousData: false }, ); }
Next.js代理工作原理与问题修复
一、Next.js代理(重写)的工作原理
Next.js的rewrites配置是服务器端生效的规则:
- 当浏览器向Next.js开发服务器(默认3000端口)发送请求时,服务器会匹配
source中的路径规则,将请求转发到destination指定的后端地址,再把后端的响应返回给浏览器。 - 整个转发过程对浏览器透明,浏览器只会和Next.js服务器通信,不会直接访问后端8000端口。
二、问题原因及修复步骤
1. 修正rewrites配置语法错误
你的next.config.js中rewrites的写法不符合规范,它需要是一个数组(支持多规则配置),而非单个对象。正确写法如下:
/** @type {import('next').NextConfig} */ const nextConfig = { rewrites: async () => [ { source: "/api/:path*", destination: "http://127.0.0.1:8000/api/:path*", }, ], }; module.exports = nextConfig;
2. 修复代码拼写错误
在api.ts中存在变量名拼写错误:你导入的是urls,但使用时写成了url.base_backend.users,这会导致请求地址无效。修正后代码:
import { useMutation, useQuery } from '@tanstack/react-query'; import urls from '../urls'; export const useUsersQuery(props = {}) => { const url = urls.base_backend.users; // 修正变量名拼写 const urlParamed = new URL(url); if (props.name) urlParamed.searchParams.append('name', props.name); return useQuery( ['useUsersQuery', ...Object.values(props)], async () => fetchWithAuth<Paginated<Excelsheet>>(urlParamed.href), { keepPreviousData: false }, ); }
3. 验证修复
修改完成后,重启Next.js开发服务器(配置变更需要重启才能生效),此时react-query发起的请求会通过Next.js代理正常转发到后端8000端口。
内容的提问来源于stack exchange,提问作者H_reugo
相关产品推荐
相关产品推荐

