简体   繁体   English

未收到带有 axios 发布请求的 Set-Cookie 标头

[英]Not Receiving Set-Cookie Header with axios post request

I have a PHP Script which successfully returns some simple Headers as well as a set-cookie header if called directly in the browser (or by postman).我有一个 PHP 脚本,如果直接在浏览器中(或由邮递员)调用,它会成功返回一些简单的标头以及 set-cookie 标头。 I can read the response-headers like that from chrome devTools.我可以从 chrome devTools 读取这样的响应头。 But as soon as I call it by Axios, the set-cookie header doesn't show up and there's no cookie saved in the browser.但是一旦我通过 Axios 调用它,set-cookie 标头就不会显示,并且浏览器中也没有保存 cookie。

I tried diffrent things like changing the response-headers server-side and using "withCredentials: true" with axios, but nothing worked.我尝试了不同的事情,比如更改响应头服务器端和使用 "withCredentials: true" 和 axios,但没有任何效果。 I don't even get an error or any cors-related problems.我什至没有收到错误或任何与 cors 相关的问题。

PHP: PHP:

header("Access-Control-Allow-Origin: http://localhost:8080");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header("Access-Control-Max-Age: 99999999");
setcookie("TestCookie", "Testing", time() + 3600, "/", "localhost", 0);
die();

JS: JS:

Vue.prototype.$http = axios.create({
    baseURL: XYZ,
    withCredentials: true
})

So my first question is why does the header appear when calling the php script directly?所以我的第一个问题是为什么直接调用php脚本时会出现header? And how can I archive to get the header through axios too?以及如何存档以通过 axios 获取标题?

probably cookie is 'httpOnly', which means client side javascript can not read it.可能 cookie 是 'httpOnly',这意味着客户端 javascript 无法读取它。 Therefore it is not showing in chrome cookie section.因此它没有显示在 chrome cookie 部分。 test the same request in mozilla, header will show up.在 mozilla 中测试相同的请求,标题会显示出来。

This may not apply to your situation, but I had the same problem using axios in this standalone nodejs script.这可能不适用于您的情况,但我在这个独立的 nodejs 脚本中使用 axios 时遇到了同样的问题。

const config = {
    url: 'https://remote.url/login',
    method: 'post',        
    headers: {
        'content-type': 'application/x-www-form-urlencoded',
    },
    data: qs.stringify({
        'email': username,
        'password': pwd
    })
}

axios(config).then(res => {
    console.log(res.headers);
}).catch(err => {
    console.log(err);
})

This returned http status 200 without set-cookie in the headers.这在标头中返回了没有set-cookie http 状态 200。 With curl the header was correctly retrieved, but the status code was 302使用 curl 正确检索了标头,但状态代码为 302

After adding the following config options to axios:将以下配置选项添加到 axios 后:

maxRedirects: 0,
validateStatus: function (status) {
    return status <= 302; // Reject only if the status code is greater than 302
  },

I received the set-cookie in axios in the response.header.我在 response.header 中的 axios 中收到了set-cookie

{
  server: 'nginx/1.16.1',
  date: 'Fri, 27 Dec 2019 16:03:16 GMT',
  'content-length': '74',
  connection: 'close',
  location: '/',
  'set-cookie': [
    'cookiename=xxxxxxxxxxxxxxxxxxxxx; path=/; expires=Sat, 26-Dec-2020 16:03:16 GMT'
  ],
  status: '302',
  'x-frame-options': 'DENY'
}

Without maxRedirects: 0 I received the html of the homepage of the remote url I used.没有maxRedirects: 0我收到了我使用的远程 url 主页的 html。

Without validateStatus I received the set-cookie header in the err.response.headers object.在没有validateStatus我在err.response.headers对象中收到了set-cookie标头。

In my case, the network panel showed that the response had the 'Set-Cookie' header, but in axios the header wouldn't show up, and the cookie was being set.就我而言,网络面板显示响应具有“Set-Cookie”标头,但在 axios 中不会显示标头,并且正在设置 cookie。

For me, the resolution was setting the Access-Control-Expose-Headers header.对我来说,解决方案是设置Access-Control-Expose-Headers标头。

Explanation:解释:

From this comment on an issue in the axios repository I was directed to this person's notes which led me to set the Access-Control-Expose-Headers header -- and now the cookie is properly setting in the client.从对 axios 存储库中某个问题的评论中,我被定向到此人的笔记,这导致我设置了Access-Control-Expose-Headers标头——现在 cookie 已在客户端中正确设置。

So, in Express.js, I had to add the exposedHeaders option to my cors middleware:因此,在 Express.js 中,我必须将exposedHeaders选项添加到我的 cors 中间件中:

const corsOptions = {
  //To allow requests from client
  origin: [
    "http://localhost:3001",
    "http://127.0.0.1",
    "http://104.142.122.231",
  ],
  credentials: true,
  exposedHeaders: ["set-cookie"],
};

...

app.use("/", cors(corsOptions), router);

It was also important that on the axios side I use the withCredentials config in following axios requests that I wanted to include the cookies.同样重要的是,在 axios 方面,我在以下 axios 请求中使用withCredentials配置,我想包含 cookie。

ex/前任/

const { data } = await api.get("/workouts", { withCredentials: true });

For me is working adding {withCredentials: true} like this:对我来说,正在像这样添加 {withCredentials: true}:

axios
.post(url, {
    foo: foo,
    baz: baz,
    }, {withCredentials: true})
.then(.............

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

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