以前,当我使用 create-react-app 制作应用程序时,我会有一个setupProxy.js
将路由与此类似的 API 请求的文件
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use('/api',
proxy({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};
但这似乎不适用于 next.js。当我做同样的事情时,我会遇到各种错误。
谷歌搜索解决方案,很多人说使用某种自定义服务器。但是我如何使用默认的 nextjs 开发服务器来完成像上面这样的代理呢? (相当于npm run dev
when dev
在我的 package.json 中是next dev
.
现在配置中有一个官方功能:Rewrites
除了正常的路径重写之外,它们还可以将请求代理到另一个网络服务器
next.config.js
:
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://localhost:8000/:path*' // Proxy to Backend
}
]
}
}
See Next.js 文档重写 https://nextjs.org/docs/api-reference/next.config.js/rewrites
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)