簡體   English   中英

我的 React 前端無法調用我的 node-express 后端服務器,全棧應用程序部署在 heroku

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM