你能提供一个示例或参考代码来说明如何在Angular4+上使用cookie执行GET和POST操作吗?在AngularJS上有相关文档,但在Angular.io文档中没有。是否有类似于"//code.angularjs.org/X.Y.Z/angular-cookies.js"这样的等效方案可以在Angular4+中使用? 谢谢。
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);
}
}
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());
如果其他人面临相同的问题。