我有一个mern社交媒体应用程序,用户可以登录,然后采取他们的饲料,他们可以创建职位,他们显示在饲料。一切都在本地主机上工作,但在服务器上,我可以登录并查看提要,甚至可以创建正在保存到数据库中的帖子,但它们不会显示在服务器上的提要上。
这是服务器。js:
const path = require('path');
const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');
const AuthRoute = require('./routes/AuthRoute.js');
const connectDB = require('./config/db.js');
const colors = require('colors');
const dotenv = require('dotenv');
dotenv.config();
const PostRoute = require('./routes/PostRoute.js');
const UploadRoute = require('./routes/UploadRoute.js');
const PORT = process.env.PORT || 8000;
connectDB();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
// Serve frontend
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../frontend/build')));
app.get('*', (req, res) =>
res.sendFile(
path.resolve(__dirname, '../', 'frontend', 'build', 'index.html')
)
);
} else {
app.get('/', (req, res) => res.send('Please set to production'));
}
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`.yellow.bold);
});
app.use('/api/auth', AuthRoute);
app.use('/api/posts', PostRoute);
app.use('/api/uploadImages', UploadRoute);
我试过把东西移来移去,但没有任何改变。这是我的PostRoutes:
const express = require('express');
const {
createPost,
getTimelinePosts,
getAllPosts,
} = require('../controllers/PostController.js');
const { authUser } = require('../middleware/auth');
const router = express.Router();
console.log('inside am in the routes');
router.post('/createPost', createPost);
router.get('/:id/timeline', getTimelinePosts);
router.get('/getAllPosts', authUser, getAllPosts);
module.exports = router;
下面是最初被调用的地方,在本地主机上,如果我注解掉除了useEffect之外的所有代码,它会在控制台中显示post数组,但在服务器控制台中显示html文档。
下面是文件:
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getTimeLinePosts } from '../../../actions/postAction';
import Post from '../Post/Post.js';
import PulseLoader from 'react-spinners/FadeLoader';
const Posts = () => {
const dispatch = useDispatch();
const { user } = useSelector((state) => state.authReducer.authData);
const { posts, loading, error } = useSelector((state) => state.postReducer);
useEffect(() => {
if (error) {
console.log(error);
}
dispatch(getTimeLinePosts(user._id));
}, [dispatch, user._id]);
return (
<div className="Posts">
{loading ? (
<div style={{ display: 'flex', justifyContent: 'center' }}>
<PulseLoader
color="#485639"
height={15}
width={5}
loading={loading}
/>
</div>
) : posts ? (
posts.map((post, i) => (
<Post key={i} post={post} index={i} user={user} />
))
) : (
"You haven't shared anything yet."
)}
</div>
);
};
export default Posts;
这里是postRequest
import axios from 'axios';
//import * as PostsApi from '../api/PostsRequests';
export const getTimeLinePosts = (id) => async (dispatch) => {
console.log(id);
const API_URL = '/api/posts/';
dispatch({ type: 'RETREIVING_START' });
try {
//const { data } = await PostsApi.getTimelinePosts(id);
const { data } = await axios.get(`/api/posts/${id}/timeline`);
console.log(data);
dispatch({ type: 'RETREIVING_SUCCESS', data: data });
} catch (error) {
dispatch({ type: 'RETREIVING_FAIL' });
console.log(error);
}
};
这是邮政减速器
const postReducer = (
state = { posts: null, loading: false, error: false, uploading: false },
action
) => {
switch (action.type) {
// belongs to PostShare.jsx
case 'ADDPOST_START':
return { ...state, error: false, uploading: true };
case 'ADDPOST_SUCCESS':
return {
...state,
posts: [action.data, ...state.posts],
uploading: false,
error: false,
};
case 'ADDPOST_FAIL':
return { ...state, uploading: false, error: true };
// belongs to Posts.jsx
case 'RETREIVING_START':
return { ...state, loading: true, error: false };
case 'RETREIVING_SUCCESS':
return {
...state,
posts: action.data,
loading: false,
error: false,
};
case 'RETREIVING_FAIL':
return { ...state, loading: false, error: true };
default:
return state;
}
};
export default postReducer;
2条答案
按热度按时间lkaoscv71#
问题是你有条件地向express管道添加了一个catch all处理程序
app.get("*")
,这将使你的API路由无法访问。express.static
中间件已经在处理Map到物理文件的路径,如果没有找到文件,它只会将请求传递给下一个中间件。一个可能的修复方法是在代码中重构,也许只是删除生产检查和捕获所有处理程序。
请注意,应该在调用
app.listen()
之前设置API路由。我不知道你为什么要在NODE_ENV中强制执行生产模式,应用程序应该在这两种环境中都能工作。
4zcjmb1e2#
在以下行之后:
Express JS根据路由在服务器文件中的写入顺序来解释路由,因此静态资产应该在所有其他路由之后提供。这应该可以解决你遇到的问题。