Home >Backend Development >Golang >Why Aren\'t My HTTPOnly Cookies Setting on Localhost?

Why Aren\'t My HTTPOnly Cookies Setting on Localhost?

Barbara Streisand
Barbara StreisandOriginal
2024-11-18 08:14:02453browse

Why Aren't My HTTPOnly Cookies Setting on Localhost?

HTTPOnly Cookie Not Being Set in Browser Localhost

Problem:

A REST API endpoint that sets an HTTPOnly cookie is not working correctly in localhost browsers.

Approaches Used:

  • Created a minimal Go and Node.js API to reproduce the issue.
  • Tested the API in Postman, where the cookie was set successfully.

Solution:

The problem lies in the front-end JavaScript's fetch() method. To receive HTTPOnly cookies in local browser environments, you must include the credentials: "include" option in the RequestInit object.

let response = await fetch(`http://localhost:8000/login`, {
  method: "POST",
  credentials: "include", //--> send/receive cookies
  body: JSON.stringify({
    email,
  }),
  headers: {
    "Content-Type": "application/json",
  },
});

For Axios, you can enable cookie handling by setting withCredentials: true in the third configuration argument.

The above is the detailed content of Why Aren\'t My HTTPOnly Cookies Setting on Localhost?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn