如何解决index.html的文件结尾会覆盖所有获取的api
我有MERN申请,我在所有路线上为index.html
服务。但是下面,我声明另一个api来请求。
router.post('/add-bin',newBin);
router.get('/recent-bins',recentBins);
router.get('/fetch-bin/:filename',fetchBin);
app.use(router);
app.get('*',(req,res) => {
res.sendFile(path.join(__dirname,'build','index.html')); // Front is built with react
});
在使用代理的开发模式下,一切都很好,但是当我将Web应用程序部署到heroku上时,所有的GET API都被app.get("*" ...)
部分覆盖。
P.S我对Node and Express还是很陌生。
解决方法
首先,在客户端运行npm run build
中,这将生成build
文件夹,其中是您的前端生产代码。在您的后端中,您应该提供该文件夹(通常将在index.js中完成)。
app.use(express.static('path/to/client/build'))
app.get('*',(req,res) => {
res.sendFile(path.join(__dirname,'build','index.html')); // Front is built with react
});
在那之后,您需要添加一些命令(在package.json中)以准备客户端进行部署。
"scripts": {
"build": "cd path/to/client && npm run build",//we'll need to install client packages
"i-client-packages": "cd client && npm install",//heroku will execute this command post-build
//this will be needed to run the previous commands
"heroku-postbuild": "npm run i-client-packages && npm run build"
//...the other commands (start,test,etc...)
}
有关如何将MERN应用程序部署到heroku here的更多信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。