nextjs:可以在不刷新的情况下获取客户侧cookie

发布于 2025-01-22 18:02:44 字数 2744 浏览 2 评论 0原文

用户登录时,我将cookie设置为js-cookie用于客户端访问。

cookie必须是-i思考 - 客户可以访问,因为我使用 redux thunk请求 s。

export async function apiLogin({ email, password }) {
  const data = JSON.stringify({
    email,
    password,
  });

  const config = {
    method: 'post',
    url: `${process.env.API_URL}/auth/login`,
    headers: {
      'Content-Type': 'application/json',
    },
    data,
  };

  const response = await axios(config);

  if (response.status === 200 && response.data) {
    const encodedUser = Buffer.from(JSON.stringify(response.data.user)).toString('base64');

    Cookies.set('token', response.data.token, { expires: 1 });
    Cookies.set('user', encodedUser, { expires: 1 });
    return { user: response.data.user, token: response.data.token };
  }
  if (response.status === 401) {
    return { error: 'User/pw incorrect' };
  }
  return { error: 'Error' };
} 

登录时正确设置了这些cookie-我可以在开发工具中的“应用程序”选项卡中看到它们。

但是,这些cookie无法访问我的未来请求:

import Cookies from 'js-cookie';

const cookieToken = Cookies.get('token') // this is throws null unless I refresh

export const axiosInstance = (token = cookieToken) => axios.create({
  baseURL: process.env.API_URL,
  headers: {
    Accept: 'application/json',
    Authorization: `Bearer ${token}`,
  },
});

示例请求:

  browse(params = {}, hook = null) {
    return axiosInstance()
      .get(endpoint, { params })
      .then((response) => {
        const { data } = response;
        if (hook) {
          data.items = data.items.map((item) => hook(item));
        }
        return data;
      })
      .catch((error) => console.error('error', error));
  },

cookie getter方法正常工作,但前提是我刷新页面。所以我认为这不是问题。

编辑:不是axios问题,我对本机fetch api做了相同的操作,但仍然无法获得cookie。我还尝试在localstorage中保存令牌,结果相同。

EDIT2:

我忘了提到我有一个_MiddleWare.js文件,仅在存在令牌时才为路由添加保护,这可以正常工作,因此我猜该服务器端可访问该令牌:

export function middleware(req) {
  const userSession = req.headers.get('cookie');
  const url = req.nextUrl.clone();

  if (userSession?.includes('token')) {
    console.log(userSession); // token is there!
    if (req.nextUrl.pathname === '/login') {
      url.pathname = '/';

      return NextResponse.redirect(url);
    }
    return NextResponse.next();
  }

  url.pathname = '/login';
  return NextResponse.rewrite(url);
}

When user logs in, I set the cookies with js-cookie for client side access.

The cookie must be -I think- client accessible since I use Redux Toolkit for async thunk requests.

export async function apiLogin({ email, password }) {
  const data = JSON.stringify({
    email,
    password,
  });

  const config = {
    method: 'post',
    url: `${process.env.API_URL}/auth/login`,
    headers: {
      'Content-Type': 'application/json',
    },
    data,
  };

  const response = await axios(config);

  if (response.status === 200 && response.data) {
    const encodedUser = Buffer.from(JSON.stringify(response.data.user)).toString('base64');

    Cookies.set('token', response.data.token, { expires: 1 });
    Cookies.set('user', encodedUser, { expires: 1 });
    return { user: response.data.user, token: response.data.token };
  }
  if (response.status === 401) {
    return { error: 'User/pw incorrect' };
  }
  return { error: 'Error' };
} 

Those cookies are correctly set upon login - I can see them in the application tab in Dev Tools.

enter image description here

However, those cookies are not accessible to my future requests:

import Cookies from 'js-cookie';

const cookieToken = Cookies.get('token') // this is throws null unless I refresh

export const axiosInstance = (token = cookieToken) => axios.create({
  baseURL: process.env.API_URL,
  headers: {
    Accept: 'application/json',
    Authorization: `Bearer ${token}`,
  },
});

Example request:

  browse(params = {}, hook = null) {
    return axiosInstance()
      .get(endpoint, { params })
      .then((response) => {
        const { data } = response;
        if (hook) {
          data.items = data.items.map((item) => hook(item));
        }
        return data;
      })
      .catch((error) => console.error('error', error));
  },

The cookie getter methods work fine, but only If I refresh the page. So I don't think that's the issue.

EDIT: Is not an axios issue, I did the same with the native fetch API and still couldn't get the cookies. I also tried saving the token in localStorage with the same result.

EDIT2:

I forgot to mention that I have a _middleware.js file that adds protection to routes only if the token is present, and this works fine, so I guess that server side the token is accessible:

export function middleware(req) {
  const userSession = req.headers.get('cookie');
  const url = req.nextUrl.clone();

  if (userSession?.includes('token')) {
    console.log(userSession); // token is there!
    if (req.nextUrl.pathname === '/login') {
      url.pathname = '/';

      return NextResponse.redirect(url);
    }
    return NextResponse.next();
  }

  url.pathname = '/login';
  return NextResponse.rewrite(url);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清醇 2025-01-29 18:02:44

好的,损失了很多时间修复此操作,这让您感到有些尴尬,但是显然,设置了一个cookie令牌,> soken 不起作用,在尝试了其他几种方法之后,它看起来就是简单地命名它cookietoken做了这项工作。 lmao。

Ok it feel kind of embarassed to have lost so much time fixing this, but apparently setting a cookie token with a name of token was not working, after trying several other methods, it looks like that simply naming it cookieToken did the work. Lmao.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文