node.js - 部署到 HEROKU 时,路由到新页面时仅从后端获取数据
问题描述
我有一个 MERN 应用程序在本地运行良好,但是当我部署到 heroku 时,当我路由到新页面时,它只显示来自后端的数据: 当路由到食谱 但是当我在本地运行时,它工作正常: 路由到食谱工作正常本地 这是我的 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 。
推荐阅读
- github - 访问回购的社交图标
- javascript - 执行后取消链接js文件
- c# - 找不到 System.Runtime.Remoting.ChannelServices
- python - 无论我更改单选按钮多少次,如何仅获取相应的输入框?
- c++ - Microsoft-STL 和 GNU-STL 之间的差异
- reactjs - 通过组件将 Props 传递给“Single Page Views”
- rust - 如何为 Rust Cargo 依赖模块选择 C/C++ 编译器
- python-3.x - python中的并发循环
- python - 如何更正这一行的缩进?
- visual-studio-code - 无法更改 VS Code 字体系列