Reputation: 1991
Can you provide an example or reference of how to use cookies on angular4+ performing GET and POST? On angularJS is documented but not on Angular.io. Any Equivalent to this: "//code.angularjs.org/X.Y.Z/angular-cookies.js" on Angular4+ Thanks in advance
Upvotes: 3
Views: 26247
Reputation: 1991
I ended up writing something like follows:
public postSomethingToServer(myUrl: string): Observable<any> {
var body = `{"username":"ddd","password":"ddd"}`;
const headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers, withCredentials: true });
return this.http.post(myUrl, body, options)
.map((response) => {
return response.json();
})
.catch(this.handleError);
}
To send the cookie in the request it was needed the (withCredentials: true) in the object passed to class RequestOptions.
For ASP Net Core apps if client and server are running on different servers needed to configure CORS
app.UseCors(config =>
config.AllowAnyOrigin()
.AllowCredentials());
In case others face the same problem.
Upvotes: 0
Reputation: 607
If you're using the new Angular 5 they introduced something called the HttpInterceptor
(https://angular.io/guide/http#intercepting-all-requests-or-responses)
What you can do is create an interceptor that gets your cookie and handles it accordingly.
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
function getCookie(name) {
const splitCookie = cookie.split(';');
for (let i = 0; i < splitCookie.length; i++) {
const splitValue = val.split('=');
if (splitValue[0] === name) {
return splitValue[1];
}
}
return '';
}
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth header from the service.
const authHeader = getCookie('auth');
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}
}
You can also use a library like this to handle cookies: https://github.com/salemdar/ngx-cookie
Upvotes: 8