我有一个React客户端和一个NODE.JS服务器。
客户端在端口3000上,服务器在5000上。
当我从客户端发出请求时,它看起来像这样:
import axios from "axios";
const axiosInstance = axios.create({
baseURL: "http://localhost:5000"
});
try {
const res = await axiosInstance.post("/api/myRoute", ....);
... more code
}
catch(...) {
}
问题是,当我将应用程序上载到Heroku时,即使我在server.js
,中,客户端也会收到404的Axios请求process.env.PORT
:
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
我们如何在Heroku上使用Axios而不指定localhost
为baseUrl
?
在开发中,当您前往时,localhost:3000
请访问使用create-react-app
脚本启动的开发服务器npm start
。然后,该服务器将您应用的开发包发送到浏览器。
您还将为api启动第二台服务器localhost:5000
。这是您的React应用程序(现在正在浏览器中运行)向本地api请求发送的服务器。
根据您的设置,您(可能)不会在生产中运行2台服务器。相反,当api路由未处理请求(因此可能是客户端路由)时,您将让您的node / express后端提供构建文件
假设项目结构如下:
-> MyCoolApp
-> index.js // express server
-> client // create-react-app application
-> src
-> index.js
-> setupProxy.js
首先进行设置http-proxy-middleware
,以使用开发和生产中的相同方式从客户端应用向服务器发出api请求axios.get('/api/route')
// place in src with index.js no need to import anywhere
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
// add other server routes to path array
app.use(proxy(['/api' ], { target: 'http://localhost:5000' }));
}
下一步设置服务器index.js,使其在生产/分阶段与开发中的行为有所不同(假设您使用的是express):
const express = require('express');
const app = express();
require('./routes')(app); //these are your api routes
//Non api requests in production
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
// Add production middleware such as redirecting to https
// Express will serve up production assets i.e. main.js
app.use(express.static(__dirname + '/client/build'));
// If Express doesn't recognize route serve index.html
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(
path.resolve(__dirname, 'client', 'build', 'index.html')
);
});
}
//start server
const PORT = process.env.PORT || 5000; //Heroku sets port dynamically
app.listen(PORT, () => {
console.log('listening...');
}).on('error', err => {
console.log(`Error Code: ${err.code}`);
});
最后,当Heroku完成根依赖关系的安装后,它将运行一个名为的脚本heroku-postbuild
,您可以指示heroku安装客户端依赖关系并构建您的生产React应用程序
在您的服务器package.json中添加/修改以下脚本:
"scripts": {
"start": "node index.js",
"server": "node index.js",
"client": "npm run start --prefix client",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
这最后一部分很有用,因为Heroku基于git,并且将构建目录/文件提交给git是一种不好的做法(gitignore
如果您将构建目录保存在本地,请确保将构建目录添加到您的目录中!)
同样,Heroku默认情况下仅安装生产依赖项(不包含任何开发依赖项),如果这是所需的行为,则可以省略 NPM_CONFIG_PRODUCTION=false
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句