我正在学习一个MERN教程,并创建了一个React站点,在那里它接收登录用户的名称和电子邮件等数据,然后显示这些数据。
这里是我的后台代码:
路由/user.js:
const express = require('express')
const userController = require('../controllers/user')
const route = express.Router()
const checkAuth = require('../middleware/auth')
route.post('/', userController.register)
route.post('/login', userController.login)
route.get('/isauth', checkAuth, userController.isAuthenticated)
route.post('/logout', checkAuth, userController.logout)
route.post('/me', checkAuth, userController.getMe)
module.exports = route
控制器/user.js:
module.exports = {
getMe: (req, res) => {
const {sub} = req.user
User.findOne({_id : sub}, (err, user) => {
if (err) {
res.status(500).json({
message : 'User not found',
data : null
})
} else {
res.status(200).json({
message : 'User found',
data : user
})
}
})
},
}
这里是我的前端代码:
authenticationAPI.js:
export const AuthenticationService = {
getMe: () => {
return axiosInstance
.get(requests.getme, { credentials: "include" })
.then((res) => {
return res;
})
.catch((err) => {
return err;
});
},
}
config/requests.js:
export const requests = {
register : '/auth',
login : '/auth/login',
logout : '/auth/logout',
getme : '/auth/me',
}
authenticationSlice.js:
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { AuthenticationService } from "./authenticationAPI";
const initialState = {
registerstatus: "",
errormessage: "",
userDetails: null,
};
//getme redux action
export const getMe = createAsyncThunk(
"users/me",
async () => {
const response = AuthenticationService.getMe();
return response;
}
);
//creation du slice
const authenticationSlice = createSlice({
name: "authentication",
initialState,
extraReducers: {
//getMe http request 3 cases
[getMe.pending]: (state, action) => {
},
[getMe.fulfilled]: (state, action) => {
console.log(action.payload);
state.userDetails = action.payload.data.data
},
[getMe.rejected]: (state, action) => {
},
export const { } = authenticationSlice.actions;
export const selectUserDetails = (state) => state.authentication.userDetails
export default authenticationSlice.reducer;
views/post/post.jsx:
import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getMe, selectUserDetails } from '../../features/authentication/authenticationSlice'
export default () => {
const dispatch = useDispatch()
useEffect(() => {
dispatch(getMe())
}, [])
const userDetails = useSelector(selectUserDetails)
return (
<h5>{userDetails && userDetails.name}</h5>
<hr />
<h6>{userDetails && userDetails.email}</h6>
)
}
电子邮件和名称仍然不呈现。
我试着在浏览器上运行这段代码,但当我登录时,在devtools控制台中出现了以下两个错误(我可以在应用程序中看到access_token(:
Error: Request failed with status code 404
GET http://localhost:5000/auth/me 404 (Not Found)
我真的很感激你的帮助。谢谢大家。
您的Express控制器只处理POST请求,因此当您尝试使用get到达该路由时,会得到404。问题源于authenticationAPI.js
:
return axiosInstance
.get(...)
// ...
只需将其更改为
return axiosInstance
.post(...)
// ...
这样,你就可以真正满足你的要求。