简体   繁体   中英

Set-Cookie header not accepted by javascript fetch

I've been trying for a couple of days now to set a cookie from my web server written in Go, and everything looks right but it just won't work.

My Set-Cookie header:

Set-Cookie: session_token=token; Path=/; Expires=Date; Max-Age=120000; HttpOnly; SameSite=Strict

I've tried editing all the values and removing and adding other fields but nothing helped. If I set my request to get and navigate directly to the link with browser cookie appears, and in Postman it is there, but when I try using fetch to get the http request it doesn't work. I know about credentials: "same-origin" and credentials: "include" but they don't work. Here is my js fetch code:

const log_in = (e) => {

 // data entry validation and stuff

 const url = "/signin";
  fetch(ip + url, {
    credentials: "same-origin",
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      username: document.getElementById("username").value,
      password: document.getElementById("password").value,
    }),
  }).then(
      () => console.log("recieved")
  );
};

This is not at all what I wanted but this is how I solved my problem if somebody is in the same boat as me... Using axios. I don't use node, yarn or whatever and using cdn gave me cors errors so I just copied the code from cdn file locally and that worked. You can se the code here:

axios({
      method: 'post',
      url: ip + url,
      data: {
        firstName: document.getElementById("username").value,
        lastName: document.getElementById("password").value
      },
      withCredentials: true
    })

I won't mark this as an answer since I wanted to do this with fetch and no 3rd party libraries but if this is someone's last resort this works...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM