我正在尝试使用Angular 2的Laravel(后端)中的服务。如果使用axios
,我可以毫无问题地使用它,但我需要使用HttpClient
我如何翻译这个代码:
const url = `${this.endPoint}/login`;
const urlCsrf = `${this.endPoint}/csrf-cookie`;
const body = { email, password };
axios.defaults.withCredentials = true;
axios.get(urlCsrf).then(() => {
axios.post(url, body).then((resp) => {
console.log(resp);
});
});
像这样的东西,但它的工作:
//this code dont work returns csrf error
this.http.get(urlCsrf).subscribe(() => {
this.http.post(url, body).subscribe((resp) => {
console.log(resp);
});
});
3条答案
按热度按时间qxsslcnc1#
我最近遇到了同样的问题,以下是对我有效的方法:
o2rvlv0m2#
该代码翻译为:
如果你想用一种更被动的方式来写:
如果你想把
withCredentials
应用到所有的请求,你应该看看评论中提到的拦截器。然后导入到
AppModule
中ogq8wdun3#
也许我迟到了,但我花了很多时间来寻找这个问题的解决方案,我想与大家分享最后的解决方案,这是正确的我。
我的设置:Angular 15-拉拉威尔10与密室。
Laravel配置:. env文件:添加行会话驱动程序= cookie会话域=本地主机
php文件添加有状态本地主机:4200(用于angular ng服务)
cors.php为凭据设置为true:
然后,在Angular 应用程序中:
1.定义拦截器如下:
导出类HttpXsrfInterceptor实现了HttpInterceptor {headerName ='X-XSRF-TOKEN';构造函数(私有令牌服务:HttpXsrf令牌提取程序){}
截取(请求:HttpRequest,下一步:HttpHandler):可观察到的{req = req.克隆({具有凭据:真,}); true, });
}}
1.在AuthService中,将登录方法设置为:
登录(登录表单:登录表单):可观察{
返回这个. http. get('http://本地主机/sancutum/csrf-cookie'). pipe(switchMap(()=〉{
}),catchError(错误=〉{控制台.错误(错误);返回throwError(错误);));
};
希望这能帮到什么人。