Mir*_*med 10 cookies typescript server-side-rendering next.js
我正在尝试从我自己的 API 中获取需要令牌的用户(我可以将令牌存储在 localStorage 或 Cookie 中)。由于使用服务器端渲染时没有本地存储访问,我必须使用cookie。但服务器中未定义 cookie。我尝试了几个 NPM 包。
我只想使用用户令牌从 Api 获取用户,所有这些都在 SSR 中。
这是我正在尝试使用的代码。
import axios from "axios";
import React from "react";
import { URLs } from "../../../app.config";
const getUser = async () => {
axios.defaults.withCredentials = true;
axios.defaults.baseURL = URLs.backend;
const token = ""; // * i need that token here
axios.defaults.headers.common["Authorization"] = "Bearer " + token;
try {
return await (
await axios.get("/user/user")
).data.user;
} catch (err: any) {
console.log(token);
console.log(err.response.data);
return null;
}
};
export default async function Login() {
const user = await getUser();
if (!user) return <div className="text-red-500">No user found</div>;
return <div>Logged in User:{JSON.stringify(user)}</div>;
}
Run Code Online (Sandbox Code Playgroud)
这是我的依赖项
"dependencies": {
"@types/node": "18.11.9",
"@types/react": "18.0.25",
"@types/react-dom": "18.0.8",
"axios": "^1.1.3",
"cookies-next": "^2.1.1",
"eslint": "8.27.0",
"eslint-config-next": "13.0.3",
"framer-motion": "^7.6.6",
"next": "13.0.3",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-icons": "^4.6.0",
"react-loader-spinner": "^5.3.4",
"socket.io-client": "^4.5.3",
"sweetalert2": "^11.6.8",
"swr": "^1.3.0",
"typescript": "4.8.4"
},
Run Code Online (Sandbox Code Playgroud)
我尝试过 npm 包
react-cookie
cookies-next
Run Code Online (Sandbox Code Playgroud)
或者有没有其他方法从用户浏览器获取cookie并使用SSR?我找到了 Next Js 12 的解决方案,但在版本 13 中没有 _app.js 文件或 getServerSideProps 函数。我想获取具有 Next Js 13 App 文件夹结构的 cookie。
Att*_*que 17
您可以从服务器端获取 Nextjs 13 中的 cookie next/headers。
例子:
import axios from "axios";
import React from "react";
import { cookies } from 'next/headers'; // Import cookies
const getUser = async () => {
const nextCookies = cookies(); // Get cookies object
const token = nextCookies.get('token') // Find cookie
if(!token) {
throw new Error("Missing token")
}
try {
const response = await axios.get("/user", {
headers: {
// NOTE: If using NextJS < 13.4.0 use:
// authorization: `bearer ${token}` // Use your cookie
authorization: `bearer ${token.value}` // Use your cookie
}
})
return response.data.user;
} catch (err: any) {
console.log(token);
console.log(err.response.data);
return null;
}
};
export default async function Login() {
const user = await getUser();
if (!user) return <div className="text-red-500">No user found</div>;
return <div>Logged in User:{JSON.stringify(user)}</div>;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20336 次 |
| 最近记录: |