brand marke
brand marke

Reputation: 459

Why is axios cookie undefined?

When I try to hit an endpoint with postman everything works, so I assume the problem is probably with my axios request as when logging req.headers.cookies on server after performing this axios request the value is undefined.

Cookies in browser work as well they are set correctly.

When i performed this request in postman the value of req.headers.cookie was fine and the request has been performed without any errors.

Client code:

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

Server code (endpoint function):

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

  ...
};

Error message: TypeError argument str must be a string. This error points to the parse function.

Has anyone experienced this before? Any ides on how I can fix this issue?

Upvotes: 0

Views: 1656

Answers (1)

gdh
gdh

Reputation: 13692

With Axios POST, 1st arg is the url, 2nd arg is data and the 3rd arg is for options.

Provide withCredentials: true in the 3rd argument of Axios.post

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

Upvotes: 3

Related Questions