GET http://localhost:5000/auth/me 404(未找到)

GET http://localhost:5000/auth/me 404 (Not Found)

我正在学习 MERN 教程并制作了一个 React 站点,它接收登录用户的 nameemail 等数据,以及然后显示这些数据。

这是我的后台代码:

routes/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

controllers/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/posts/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>
    )
}

emailname 仍然没有呈现。

我尝试在浏览器上运行这段代码,但是当我登录时,我在 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(...)
  // ...

这样您就可以按照您的要求实际到达路线。