[英]Express routing for single page app doesn't seem to work
I have simple server.js file as follows: 我有简单的server.js文件,如下所示:
const express = require('express');
const app = express();
app.set('port', (process.env.PORT || 3031));
if (process.env.NODE_ENV === 'production') {
app.use(express.static('build'));
app.get('*', (req, res) => {
res.sendFile('build/index.html');
})
}
app.listen(app.get('port'), (error) => {
if (error) return console.error(error.message);
console.log(`Server started at: http://localhost:${app.get('port')}/`);
})
I expect it to re-route all paths to index.html in production and start a server. 我希望它可以将生产中的所有路径重新路由到index.html并启动服务器。 At the moment routing bit seems to not work, as I am getting following error: 目前路由位似乎不起作用,因为我收到以下错误:
Server started at: http://localhost:3031/ TypeError: path must be absolute or specify root to res.sendFile 服务器从以下位置启动: http:// localhost:3031 / TypeError:路径必须是绝对路径或将根目录指定为res.sendFile
尝试将根目录添加到路径
res.sendFile(__dirname + '/build/index.html');
res.sendFile
requires an absolute path, just as the error says. res.sendFile
需要绝对路径,正如错误所示。
Try using the __dirname global : 尝试使用__dirname global :
res.sendFile(__dirname + 'build/index.html');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.