【问题标题】:When route to a new page get only data from backend when deploy to HEROKU部署到HEROKU时,路由到新页面时仅从后端获取数据
【发布时间】:2021-08-08 06:35:43
【问题描述】:

我有一个 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\""
  }, 
}

【问题讨论】:

    标签: node.js reactjs heroku mern


    【解决方案1】:

    嗯,问题是一旦应用程序部署到 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

    【讨论】:

    • 有什么方法可以让我的服务器和前端运行在 2 个不同的端口上?
    猜你喜欢
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2019-12-24
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多