我正在使用 pm2 将我的 MERN 应用程序作为一个进程运行,当我curl http://localhost:3000
在控制台中输入时,输出确实来自我的应用程序。但 nginx 反向代理不起作用。该应用程序在 vps 上运行并连接到域名。但我从浏览器中收到“重定向您太多次。”。
服务器.js
const PORT = 3000
const app = express()
const router = express.Router()
const { persistor, store } = createPersistor()
const serverRenderer = (req, res, next) => {
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '../build/index.html'), function (err) {
if (err) {
res.status(500).send(err)
}
})
})
const context = {}
fs.readFile(path.resolve('./build/index.html'), 'utf8', (err, data) => {
if (err) {
console.error(err)
return res.status(500).send('An error occurred')
}
return res.send(
data.replace(
'<div id="root"></div>',
`<div id="root">
${ReactDOMServer.renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</StaticRouter>
</Provider>
)}
</div>`
)
)
})
}
router.use('^/$', serverRenderer)
router.use(
express.static(path.resolve(__dirname, '..', 'build'))
)
app.use(router)
app.listen(PORT, () => {
console.log(`SSR running on port ${PORT}`)
})
nginx/站点可用/默认:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name 198.51.100.255;
return 302 $scheme://mysite.com$request_uri;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
并且没有错误日志。
注意:我还没有配置 SSL。