小编Mir*_*med的帖子

如何在服务器端渲染的 Next Js 13(测试版)中获取 cookie

我正在尝试从我自己的 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 …
Run Code Online (Sandbox Code Playgroud)

cookies typescript server-side-rendering next.js

10
推荐指数
1
解决办法
2万
查看次数