简体   繁体   English

Set-Cookie header 未通过 Azure 函数传递

[英]Set-Cookie header not being passed with Azure Functions

I am trying to write an Azure Function which will set a HttpOnly cookie in the user's browser but it is not working.我正在尝试编写一个 Azure Function 它将在用户的浏览器中设置一个 HttpOnly cookie,但它不起作用。 In Postman I can see the Set-Cookie header in the response, but this header is omitted when testing the function in the browser.在Postman中可以看到响应中的Set-Cookie header,但是在浏览器中测试function时省略了这个header。

Here are the Headers returned to the browser: headers: {content-length: "13", content-type: "text/html; charset=utf-8"}以下是返回给浏览器的标头: headers: {content-length: "13", content-type: "text/html; charset=utf-8"}

Here is my code:这是我的代码:

Azure Function Code Azure Function 代码

module.exports = function (context, req) {
  context.log('JavaScript HTTP trigger function processed a request.');

  context.res = {
    status: 200,
    headers: {
      "Content-Type": "text/html",
      "Set-Cookie": "a=b; httpOnly",
    },
    
    body:
      'Body Response'
  };
  context.done();
}

Node Code节点代码

const createCookieAzure = () => {
  return new Promise((resolve, reject) => {

    console.log("Inside create cookie promise");

    axios({
      url: 'http://localhost:7071/api/SetHttpOnlyCookie',
      method: 'GET',
    })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });
  })
}

const createHttpOnlyCookie = async (e) => {
  e.preventDefault();
  console.log("Button clicked");
  await createCookieAzure();
  console.log("After createcookie");
}

In the above code createHttpOnlyCookie() is triggered by the onClick of a button component.在上面的代码中,createHttpOnlyCookie() 是由按钮组件的 onClick 触发的。

For this problem, I think you need to check if the cookie created in your browser first.对于这个问题,我认为你需要先检查浏览器中是否创建了cookie。 You can go to your browser "Settings" --> search "cookie" --> "Cookies and site data" --> "See all cookies and site data" --> then search your cookie.您可以go到您的浏览器“设置”-->搜索“cookie”-->“Cookies和站点数据”-->“查看所有cookies和站点数据”-->然后搜索你的cookie。

I guess when you request the function by axios, it will not add the cookie to your browser because set cookie in a api and request it in axios is not same as request by browser (if the cookie has been added in browser, everything is ok, please ignore the rest).我想当你通过 axios 请求 function 时,它不会将 cookie 添加到你的浏览器,因为在 api 中设置 cookie 并在 axios 中请求它与浏览器请求不同(如果浏览器中已添加 cookie,则一切正常,请忽略其余部分)。 If you don't find the cookie in your browser, I think you need to add another header in your axios request like below code:如果您在浏览器中找不到 cookie,我认为您需要在axios请求中添加另一个 header,如下代码所示:

axios({
  method: 'get',
  url: '....',
  headers: {'header1': value}
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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