首页 > 解决方案 > 为什么 axios cookie 未定义?

问题描述

当我尝试使用邮递员访问端点时,一切正常,所以我认为问题可能出在我的 axios 请求上,因为req.headers.cookies在执行此 axios 请求后登录服务器时,值是undefined.

浏览器中的 Cookie 也可以正常工作,它们设置正确。

当我在邮递员中执行此请求时,值req.headers.cookie很好,并且请求已执行且没有任何错误。

客户端代码:

  useEffect(() => {
    (async () => {
      const res = await axios.post('http://localhost:4000/refresh_token', {
        withCredentials: true,
      });
    })();
  }, []);

服务器代码(端点函数):

export const validateRefreshToken = async (req, res) => {
  console.log(req.headers.cookie); // undefined
  const { token } = parse(req.headers.cookie);

  ...
};

错误信息:TypeError argument str must be a string. 此错误指向解析函数。

有谁之前经历过这个吗?关于如何解决此问题的任何想法?

标签: node.jsreactjsexpresscookiesaxios

解决方案


在 AxiosPOST中,第一个参数是url,第二个参数是data,第三个参数是 for options

withCredentials: true在第三个参数中提供Axios.post

  useEffect(() => {
    (async () => {
      const res = await axios.post('http://localhost:4000/refresh_token', {} ,{
        withCredentials: true,
      });
    })();
  }, []);

推荐阅读