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的更多信息。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...