【发布时间】:2017-12-04 19:29:21
【问题描述】:
您能否提供一个示例或参考,说明如何在 angular4+ 上使用 cookie 执行 GET 和 POST?在 angularJS 上有文档,但在 Angular.io 上没有。 任何等效于此:Angular4+上的“//code.angularjs.org/X.Y.Z/angular-cookies.js” 在此先感谢
【问题讨论】:
您能否提供一个示例或参考,说明如何在 angular4+ 上使用 cookie 执行 GET 和 POST?在 angularJS 上有文档,但在 Angular.io 上没有。 任何等效于此:Angular4+上的“//code.angularjs.org/X.Y.Z/angular-cookies.js” 在此先感谢
【问题讨论】:
如果您使用的是新的 Angular 5,他们引入了称为 HttpInterceptor (https://angular.io/guide/http#intercepting-all-requests-or-responses) 的东西
您可以做的是创建一个拦截器来获取您的 cookie 并相应地处理它。
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);
}
}
您还可以使用这样的库来处理 cookie: https://github.com/salemdar/ngx-cookie
【讨论】:
我最终写了如下内容:
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);
}
要在请求中发送 cookie,需要传递给类 RequestOptions 的对象中的 (withCredentials: true)。
对于 ASP Net Core 应用程序,如果客户端和服务器运行在需要配置 CORS 的不同服务器上
app.UseCors(config =>
config.AllowAnyOrigin()
.AllowCredentials());
以防其他人面临同样的问题。
【讨论】: