![](/img/trans.png)
[英]React fullstack architecture: When adding a react front-end to a node/express application, what aspects does react's state generally handle?
[英]My React front-end is unable to call my node-express backend server, the fullstack app is deployed in heroku
const port = process.env.PORT || ("http://localhost:3002")
const postUrl=`${port}/post`;
addData=()=>{
console.log(postUrl)
console.log(process.env,"AS")
Axios.post(postUrl,this.state.form)
.then((response)=>{
this.setState({errorMessage:"",successMessage:response.data})})
.catch((err)=>{
this.setState({successMessage:"",errorMessage:err.response.data.message})
})
}
当我在生产过程中调用后端时,env.PORT 是空白的。
(process.env.NODE_EV=production,完全正确,就像后端一样)
我的后端完全没问题,因为它正确获取了 process.env.PORT。 但是我的前端没有得到 process.env.PORT 这就是为什么它一直调用另一个地址(“http://localhost:3002”)。
如果我保持打开本地计算机后端,应用程序将完全正常工作,因为“http://localhost:3002”可以提供服务。 但在生产中,Heroku 不断更改 process.env.PORT,它在后端显示其价值,而不是在前端
如何让我的前端在生产中正确调用我的后端服务器?
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const port = process.env.PORT || 3002;
const cors = require("cors");
const path=require("path");
const routing = require("./routing/route");
require('dotenv').config();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/",routing);
app.use(function (err, req, res, next) {
console.log("hii")
res.status(500).send({ message: err.message });
});
if(process.env.NODE_ENV ==="production"){
app.use(express.static("client/build"));
app.get("*",(req,res)=>{
res.sendFile(path.resolve((__dirname,"client","build","index.html")));
});
}
app.listen(port, () => {
console.log(` Server is started at http://localhost:${port}`);
});
服务器文件
如果如您所说,您的 React 应用程序是从您的 Node.JS 应用程序提供的,您可以只使用window.location
。 window.location
是一个 object 存储有关用户当前页面的统计信息,您可以使用它来构造 URL 并向服务器发送请求,例如:
// This URL uses a template literal, which is a new feature of ES6.
// All but Internet Explorer supports it.
// This is using window.location.protocol, which is either `http:` or `https:`,
// depending on the protocol that the page was loaded with. window.location.host
// is the host that the page was loaded from, with the port number.
const postUrl =
`${window.location.protocol}//${window.location.host}/post`;
// And then requesting with the URL.
addData = () => {
console.log(postUrl);
console.log(process.env, "AS");
Axios.post(postUrl, this.state.form)
.then((response) => {
this.setState({errorMessage: "",successMessage: response.data});
})
.catch((err) => {
this.setState({successMessage: "",errorMessage: err.response.data.message});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.