当路由到新页面时,仅在部署到 HEROKU 时从后端获取数据

When route to a new page get only data from backend when deploy to HEROKU

我有一个 MERN 应用程序在本地运行良好,但是当我部署到 heroku 时,当我路由到一个新页面时,它只显示来自后端的数据: when route to recipes 但是当我 运行 本地时,它工作正常: route to recipes working fine on local 这是我的 MERN 应用程序的 link:

https://foodrecipegroup3.herokuapp.com/

谁能帮我找出问题所在? 这是我的 server.js

代码
const express = require('express');
const bodyParser = require('body-parser');
const routesHandler = require('./routes/handler.js');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
require('dotenv/config');

mongoose.connect(process.env.DB_URI || 'mongodb+srv://HUYDQ184271:huycoihthd123@cluster0.cmcyc.mongodb.net/myFirstDatabase?retryWrites=true&w=majority', {
    useNewUrlParser:true,
    useUnifiedTopology:true,
    useCreateIndex:true
})
.then( () => {
    console.log('DB connected');
})
.catch( (err) => {
    console.log(err);
})

const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(cors());
app.use('/',routesHandler);

const PORT = process.env.PORT || 4000;

if(process.env.NODE_ENV === 'production'){
    //set static folder
    app.use(express.static('frontend/build'));
}
app.get('*',(req, res) => {
    res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'));
});

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}.`);
})

这是我的 package.json 在根文件夹

{
  "name": "backend",
  "version": "1.0.0",
  "main": "index.js",

  "scripts": {
    "server": "nodemon index.js",
    "start": "node index.js",
    "build": "cd frontend && npm run build",
    "install-client": "cd frontend && npm install",
    "heroku-postbuild": "npm run install-client && npm run build",
    "client": "npm run start --prefix frontend",
    "dev": "concurrently --kill-others-on-fail \"npm run server\" \"npm run client\""
  }, 
}

好吧,问题是一旦应用程序部署到 Heroku 或任何其他平台,就没有本地主机的概念。 localhost 仅存在于您的本地环境中。所以你的 Axios 应该发送一个请求到

axios.post('/receipies', receipies);
//instead of

axios.post('http://localhost:5000/receipies', receipies);

因为所有东西都在一个端口上 运行,Axios 会自动将路由附加到 URL。

我的意思是,如果您的 Heroku 应用在 https://foodrecipegroup3.herokuapp.com/(example)

上 运行

调用该路线后,您的 URL 将是 https://foodrecipegroup3.herokuapp.com/recipes