Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

node.js - Angularjs $http does not seem to understand "Set-Cookie" in the response

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.

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

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

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);
});

Thank you for your help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

Example:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...