Last active
March 20, 2023 09:20
-
-
Save avaforvr/c7d40891e56a5a956139ce417aa90fb5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const next = require('next'); | |
const { parse } = require('url'); | |
const { createProxyMiddleware } = require('http-proxy-middleware'); | |
const devProxy = module.exports = { | |
'/web': { | |
target: 'https://api.xxx.com', | |
pathRewrite: { '/web/': '/' }, | |
changeOrigin: true | |
} | |
}; | |
const rewriteRules = { | |
flexstarProduct: { | |
re: /^(\/..)?\/xxx-([\w-]+)?-yyy(.*)$/, | |
replacement: '/product/$2$3' | |
}, | |
}; | |
const nextServer = async (port) => { | |
const isDev = process.env.NODE_ENV !== 'production'; | |
const nextServer = next({ dev: isDev }); | |
const handler = nextServer.getRequestHandler(); | |
function render(req, res, url) { | |
const parsed = parse(url, true); | |
// 中间件创建的 query 与 url 中的 query 合并 | |
parsed.query = Object.assign({}, req.query, parsed.query); | |
return handler(req, res, parsed); | |
} | |
//prepare or make the next.js code ready to use another server for handling SSR | |
const app = express(); | |
await nextServer.prepare(); | |
// 开发模式反向代理 | |
if (isDev || process.env.NEXT_PUBLIC_ENV_NAME === 'dev') { | |
Object.keys(devProxy).forEach(key => { | |
app.use(key, createProxyMiddleware(devProxy[key])); | |
}); | |
} | |
// rewrite path, 对应网站 nginx 配置中的 rewrite | |
Object.keys(rewriteRules).forEach(key => { | |
const rule = rewriteRules[key]; | |
app.get(rule.re, function (req, res) { | |
let url = req.url.replace(rule.re, rule.replacement); | |
// 替换后url中有多个问号的情况 | |
if (url.includes('?')) { | |
const [pathname, ...params] = url.split('?'); | |
url = pathname + '?' + params.join('&'); | |
} | |
return render(req, res, url); | |
}); | |
}) | |
// 检测服务端是否成功启动 | |
app.get('/health', (req, res) => res.send('success')); | |
app.get('*', (req, res) => render(req, res, req.url)); | |
app.post('*', (req, res) => render(req, res, req.url)); | |
await app.listen(port); | |
console.log(`> Ready on http://localhost:${port}`); | |
}; | |
module.exports = nextServer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment