[英]How to connect a frontend application on a different port with a backend?
I put my frontend application in the public folder for a node.js application and am getting the form-data using the following request:我将前端应用程序放在 node.js 应用程序的公共文件夹中,并使用以下请求获取表单数据:
try {
await axios.post("/api/v1/contact-form", {
name,
email,
msg,
});
}
My backend is in port 5000 and it's handling the request by:我的后端位于端口 5000 中,它通过以下方式处理请求:
app.use("/api/v1/contact-form", submitFormRouter);
It works perfect.它工作完美。 I'm getting the data when I have my frontend application is in the node.js public folder.当我的前端应用程序位于 node.js 公用文件夹中时,我正在获取数据。
My question is if my frontend is running on a different local port such as, if I use "Five server" to run the frontend application, how do I replace the following path for post:我的问题是我的前端是否在不同的本地端口上运行,例如,如果我使用“五台服务器”来运行前端应用程序,我如何替换以下路径来发布:
Frontend:前端:
try {
await axios.post("/api/v1/contact-form", {
name,
email,
msg,
});
}
Backend:后端:
app.use("/api/v1/contact-form", submitFormRouter)
I've also tried the code using React in which case the frontend is running in http://localhost:3000/
and node.js server running in 5000
, the code still works and I'm getting the form data.我还尝试了使用 React 的代码,在这种情况下,前端在http://localhost:3000/
中运行,node.js 服务器在5000
中运行,代码仍然有效,我正在获取表单数据。 But, how do I make it work for a frontend application sitting in a different port(without react)?但是,如何使它适用于位于不同端口的前端应用程序(没有反应)?
Additionally, I hope you're kind enough to answer the following question- What would be the path once I have the frontend let's say on Netlify whereas the backend is on Heroku?此外,我希望您能很好地回答以下问题 - 一旦我拥有前端,让我们在 Netlify 上说,而后端在 Heroku 上,路径会是什么?
What would be the path once I have the frontend let's say on Netlify whereas the backend is on Heroku?一旦我在 Netlify 上说前端,而后端在 Heroku 上,路径会是什么?
Let's assume your Back on Heroku has this url https://app.herokuapp.com/
and the Front on Netlify this one https://app.netlify.com/
.假设您在 Heroku 上的 Back 有这个网址https://app.herokuapp.com/
和 Netlify 上的 Front https://app.netlify.com/
。 All you have to do is to give your Front your Back's url, like so:你所要做的就是给你的 Front 你的 Back 的 url,像这样:
try {
await axios.post("https://app.herokuapp.com/api/v1/contact-form", {
name,
email,
msg,
});
}
My question is if my frontend is running on a different local port such as, if I use "Five server" to run the frontend application, how do I...我的问题是我的前端是否在不同的本地端口上运行,例如,如果我使用“五台服务器”来运行前端应用程序,我该如何...
At this point you have two choices, the simplest one is to use a complete url like above.此时您有两种选择,最简单的一种是使用上面的完整 url。 Let's assume your Front is on port 3000
and the Back on 8080
.假设您的 Front 位于端口3000
上,而 Back 位于8080
端口上。 All you have to do again is:你所要做的就是:
try {
await axios.post("http://localhost:8080/api/v1/contact-form", {
name,
email,
msg,
});
}
The second one is to use a proxy
, and this really depends on your projects' structure and need.第二种是使用proxy
,这实际上取决于您项目的结构和需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.