Ara*_*oca 5 proxy node.js next.js
使用 next.js 版本8.0.3
我不知道如何在具有不同子路径的代理下提供自定义服务器。
我正在做:
npm run build && npm start
以便构建并开放自定义服务器。
我没有打开http://localhost:3000 ,而是使用带有另一个子路径http://localhost:8000/example 的代理。
代理很简单,重现它:
代理.js
const express = require('express')
const proxy = require('http-proxy-middleware')
const options = {
target:'http://localhost:3000/',
}
const exampleProxy = proxy(options)
const app = express()
app.use('/example', exampleProxy)
app.listen(8000)
Run Code Online (Sandbox Code Playgroud)
进而:
node proxy.js
Run Code Online (Sandbox Code Playgroud)
但是,当我打开http://localhost:8000/example url 时,正在加载主页,但没有样式、静态、javascript...任何东西...
我怎样才能正确地做到这一点?
太感谢了!
作为警告,我首先要说的是,我不相信 NextJS 能很好地处理代理,尤其是在子路径上。
话虽这么说,以下内容应该有效,但有限制:
const express = require('express')
const proxy = require('http-proxy-middleware')
const options = {
target:'http://localhost:3000/',
pathRewrite: {
'^/example': ''
}
}
const exampleProxy = proxy(options)
const app = express()
app.use(['/example', '/_next', '/static'], exampleProxy)
app.listen(8000)
Run Code Online (Sandbox Code Playgroud)
pathRewrite 选项确保/example/xyz
代理重定向到/xyz
您的 NextJS 服务器。
您需要代理/_next
(或者您将构建目录重命名为的任何内容),以便您的页面找到所有构建的资产(脚本、样式表、webpack 块等)。如果您检查 Next 的任何项目页面,您会发现这些资产链接是绝对的,因此也需要代理该目录。
出于同样的原因,您需要代理/static
,只不过该目录用于保存静态 NextJS 资产(图像等)。
您还会注意到“下一步”中的页面链接通常也是绝对的(我知道我的页面链接在我的所有项目中)。
以上就是我说的原因,在我看来,NextJS 并不真正适合子路径代理的使用。
更新:
next.config.js
您可以在NextJS 项目根目录的文件中添加以下配置:
module.exports = {
assetPrefix: '/example'
}
Run Code Online (Sandbox Code Playgroud)
这将添加/example
到所有已构建的资源之前,因此/_next/pages/xyz
您将链接到/example/_next/pages/xyz
. 通过此更新,您可以删除/_next
代理端的代理,并且您的可构建资产(脚本、样式表等)仍应加载。
关于 NextJS 应用程序中的导航(即“页面”)链接,如我的评论中所述,您可以设置自己的版本Link
并在子路径前面添加:
import Link from 'next/link'
// for proxied server
const PROXY_PATH= '/example'
// for non-proxied server
// const PROXY_PATH= ''
export default MyLink = ({ as, children, ...props }) => <Link {...props} as={`${PROXY_PATH}${as}`}>{children}</Link>
Run Code Online (Sandbox Code Playgroud)
您必须确保所有MyLink
组件都定义了一个as
prop。您不想更改道具本身(原样href
的链接),而只想更改道具(显示的链接)。as
最后,对于/static
资产,您只需在 NextJS 应用程序中重写静态链接,即:
<img src='/static/mylogo.svg' />
Run Code Online (Sandbox Code Playgroud)
到
<img src=`${PROXY_PATH}/static/mylogo.svg` />
Run Code Online (Sandbox Code Playgroud)
并且代理端的路径重写应该正确处理它。这样,您可以PROXY_PATH
在单独的配置文件中在项目范围内定义或从环境变量加载它。
归档时间: |
|
查看次数: |
6116 次 |
最近记录: |