我正在關注 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
})
}
})
},
}
這是我的前面代碼:
身份驗證API.js:
export const AuthenticationService = {
getMe: () => {
return axiosInstance
.get(requests.getme, { credentials: "include" })
.then((res) => {
return res;
})
.catch((err) => {
return err;
});
},
}
配置/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;
意見/帖子/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)
我真的很感謝你的幫助。謝謝你們。
uj5u.com熱心網友回復:
您的 Express 控制器僅處理 POST 請求,因此當您嘗試使用 GET 訪問該路由時會得到 404。問題源于authenticationAPI.js:
return axiosInstance
.get(...)
// ...
只需將其更改為
return axiosInstance
.post(...)
// ...
這樣,您就可以根據您的請求實際到達路線。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/450893.html
標籤:javascript 反应 验证 反应还原
