Angularjs $http 似乎不理解“Set-Cookie";在回应中 [英] Angularjs $http does not seem to understand "Set-Cookie" in the response

查看:23
本文介绍了Angularjs $http 似乎不理解“Set-Cookie";在回应中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有用于身份验证的 Passport 模块的 nodejs express REST api.登录方法 (GET) 在标头中返回一个 cookie.当我从 Chrome 调用它时它工作正常,我的 cookie 设置在我的浏览器中.

I have a nodejs express REST api with Passport module for authentication. A login method (GET) returns a cookie in the header. When I call it from Chrome it works fine, my cookie is set in my browser.

但是如果我从 Angularjs 通过 $http 调用它,cookie 没有设置.

But if I call it through $http from Angularjs, the cookie is not set.

Set-Cookie:connect.sid=s%3Ad7cZf3DSnz-IbLA_eNjQr-YR.R%2FytSJyd9cEhX%2BTBkmAQ6WFcEHAuPJjdXk3oq3YyFfI; Path=/; HttpOnly

如上所示,Set-Cookie 存在于 http 服务响应的标头中.

As you can see above, the Set-Cookie is present in the header of the http service response.

也许 HttpOnly 可能是这个问题的根源?如果是,我该如何更改?这是我的快速配置:

Perhaps HttpOnly may be the source of this problem? If yes, how can I change it? Here is my express configuration :

app.configure(function () {
    app.use(allowCrossDomain);
    app.use(express.bodyParser());
    app.use(express.cookieParser())
    app.use(express.session({ secret: 'this is a secret' }));
    app.use(flash());
    //passport init
    app.use(passport.initialize());
    app.use(passport.session());
    app.set('port', process.env.PORT || 8080);
});

感谢您的帮助

推荐答案

确保将您的 $http 请求配置为使用凭据.来自 XHR 文档:

Make sure to configure your $http request to use credentials. From the XHR documentation:

https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

XMLHttpRequest 和访问控制是发出凭据"请求的能力识别 HTTP Cookie 和 HTTP 身份验证信息.经过默认情况下,在跨站点 XMLHttpRequest 调用中,浏览器不会发送凭据.必须在 XMLHttpRequest 上设置特定标志对象被调用时.

The most interesting capability exposed by both XMLHttpRequest and Access Control is the ability to make "credentialed" requests that are cognizant of HTTP Cookies and HTTP Authentication information. By default, in cross-site XMLHttpRequest invocations, browsers will not send credentials. A specific flag has to be set on the XMLHttpRequest object when it is invoked.

您可以使用选项对象来设置凭据的使用,请参阅

You can use the options object to set the use of credentials, see

http://docs.angularjs.org/api/ng.$http

示例:

$http({withCredentials: true, ...}).get(...)

这篇关于Angularjs $http 似乎不理解“Set-Cookie";在回应中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆