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

问题描述

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

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 的概念。 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