我正在使用 create-react-app(所以没有自定义 webpack)和节点服务器构建一个 MERN 应用程序。我正在使用 nodemon 重新启动后端的更改,问题是大约一半的时间似乎我的前端在 nodemon 可以重新启动节点服务器之前尝试渲染,从而导致 ECONNREFUSED 错误。
我可以通过简单地刷新页面来解决这个问题,但是必须反复这样做很烦人,我想弄清楚问题可能是什么。如果我运行节点服务器而不是 nodemon,则不会发生这种情况。
这是我的客户端 package.json 的相关部分:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:7777"
和服务器端 package.json:
"scripts": {
"client-install": "npm intall --prefix client",
"start": "node server.js",
"server": "nodemon server.js",
"client": "cd client && npm start",
"dev": "concurrently \"npm run server\" \"npm run client\""
}
和我的 server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const path = require('path');
const routes = require('./routes/index');
require('dotenv').config();
const app = express();
app.use(bodyParser.json());
mongoose.connect(process.env.DATABASE, {useNewUrlParser: true})
.then(() => console.log('MongoDb connected'))
.catch(err => console.log(`Mongo error ${err}`))
const port = process.env.PORT || 7777;
app.use('/', routes);
if (process.env.NODE_ENV === 'production') {
// Serve any static files
app.use(express.static(path.join(__dirname, 'client/build')));
// Handle React routing, return all requests to React app
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
app.listen(port, () => {
console.log(`Connected at port ${port}`)
})
我将 axios 用于我的前端 HTTP 请求:
import axios from 'axios';
import FormData from 'form-data'
import keys from '../keys';
export const getPosts = () => {
return axios.get('/api')
}
export const post = (file, bodyInfo) => {
let formData = new FormData();
formData.append('file', file[0], file[0].name);
formData.append('bodyInfo', JSON.stringify(bodyInfo));
return axios.post('/api', formData, {
headers: {
'Content-Type': `multipart/form-data;
boundary=${formData._boundary}`,
}
})
}
export const getSinglePhoto = (id) => {
return axios.get(`/api/${id}`);
}
export const postUser = (userDetails) => {
console.log(userDetails);
return axios.post('/api/user', userDetails)
}
export const getUser = () => {
return axios.get('/user');
}
export const removeUser = (id) => {
return axios.delete(`/user/${id}`)
}
这是我的路线:
router.get('/api', postController.getPosts);
router.post('/api',
postController.type,
postController.uppic,
postController.cloudinary
);
router.get('/api/:id', postController.getSingle);
router.get('/user', userController.getUser);
router.post('/api/user', userController.postUser);
router.delete('/user/:id', userController.removeUser);