以下是如何使用正确的代码格式在 Stack Overflow 上发布问题的方法:
我在 Next.js 14 应用程序中遇到客户端数据获取问题。具体来说,我尝试使用组件内的 Axios 从后端 API 获取用户配置文件数据,但未检索到数据。
预期行为: 该组件应在前端显示从后端检索的用户名。尽管使用 Postman,API 调用工作得非常好,并且当直接在新选项卡上请求服务器时,它也可以工作并从
http://localhost:8080/api/v1/profile
发回用户数据。然而,在前端使用 Axios 会返回 undefined。
这是我的代码:
"use client";
import React, { useState, useEffect } from "react";
import axios from "axios";
const Page = () => {
const [count, setCount] = useState(null);
const [userProfile, setUserProfile] = useState(null);
useEffect(() => {
const savedValue = localStorage.getItem("jwt");
setCount(savedValue);
}, []);
const getUserProfile = async () => {
try {
const token = count;
if (!token) {
console.error("No token found in local storage");
return;
}
const response = await axios.get("http://localhost:8080/api/v1/profile", {
headers: { Authorization: `Bearer ${token}` },
});
setUserProfile(response.data);
// console.log(response); // It always logs undefined
} catch (error) {
console.error("Error fetching user profile:", error);
}
};
useEffect(() => {
getUserProfile()
)
}, [count]); // Trigger useEffect when count changes (i.e., token retrieval)
return (
<div>
user dashboard: {userProfile && userProfile.name}
</div>
);
};
export default Page;
问题: 使用 Axios 从后端 API 获取数据时,出现用户配置文件数据未定义的错误。即使请求在 Postman 和新的浏览器选项卡中工作得很好,也会发生这种情况。
错误消息: 控制台日志显示响应始终未定义。
有人可以帮我解决这个问题吗?关于可能导致无法在我的 Next.js 应用程序中检索数据的任何建议?
提前谢谢您!
检查
localStorage.getItem('jwt')
是null
还是string
。
对于token,你可以使用axios的请求拦截器使代码更简单:
'use client';
import React, { useState, useEffect } from 'react';
import axios from 'xior';
function getToken() {
return localStorage.getItem('jwt');
}
axios.interceptors.request.use((config) => {
const token = getToken();
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
const Page = () => {
const [userProfile, setUserProfile] = useState(null);
const getUserProfile = async () => {
try {
const response = await axios.get('http://localhost:8080/api/v1/profile');
setUserProfile(response.data);
// console.log(response); // It always logs undefined
} catch (error) {
console.error('Error fetching user profile:', error);
}
};
useEffect(() => {
if (getToken()) {
getUserProfile();
}
}, []); // Trigger useEffect when count changes (i.e., token retrieval)
return <div>user dashboard: {userProfile && userProfile.name}</div>;
};
export default Page;