无法获取用户 ID - 404 未找到用户

Cannot get user id - 404 User not found

当我导航到 user/dashboard 时,我应该在 url 末尾看到用户 ID,但我看到的是 http://localhost:3000/profile/$%7B_id%7D,无论谁登录,我都得到404 错误响应:error: "User not found"。我不知道 $%7B_id%7D 来自哪里。

我需要在我的代码中更改什么才能解决此问题并获得正确的用户 ID?

export const isAuthenticated = () => {
    if (typeof window == 'undefined') {
        return false;
    }
    if (localStorage.getItem('jwt')) {
        return JSON.parse(localStorage.getItem('jwt'));
    } else {
        return false;
    }
};

apiUser.js

import { API } from "../config";

export const read = (userId, token) => {
    return fetch(`${API}/user/${userId}`, {
        method: "GET",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`
        }
    })
        .then(response => {
            return response.json();
        })
        .catch(err => console.log(err));
};

export const update = (userId, token, user) => {
    return fetch(`${API}/user/${userId}`, {
        method: "PUT",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`
        },
        body: JSON.stringify(user)
    })
        .then(response => {
            return response.json();
        })
        .catch(err => console.log(err));
};

export const updateUser = (user, next) => {
    if (typeof window !== "undefined") {
        if (localStorage.getItem("jwt")) {
            let auth = JSON.parse(localStorage.getItem("jwt"));
            auth.user = user;
            localStorage.setItem("jwt", JSON.stringify(auth));
            next();
        }
    }
};

UserDashboard.js

const Dashboard = () => {
  const {
    user: { _id, name, email, role }
  } = isAuthenticated();

  const userLinks = () => {
    return (
            <Link className="nav-link" to="/profile/${_id}">
              Update Profile
            </Link>
    );
  };

问题是这个函数:

export const isAuthenticated = () => {
    if (typeof window == 'undefined') {
        return false;
    }
    if (localStorage.getItem('jwt')) {
        return JSON.parse(localStorage.getItem('jwt'));
    } else {
        return false;
    }
};

returns 布尔值

但在这里:

  const {
    user: { _id, name, email, role }
  } = isAuthenticated();

你正试图从中抽象出 _id 而它不知道 _id 是什么。所以如果你要解构

,你需要确保它 returns 是一个带有这些键的对象

我在这里使用 _id 时忘记使用模板字符串和 {}to="/profile/${_id}">

更改为:to={`/profile/${_id}`}> 并且 _id 正在运行。