在 Angular 6 中添加 Xsrf-Token 的问题 [英] Issue in adding Xsrf-Token in an Angular 6

查看:22
本文介绍了在 Angular 6 中添加 Xsrf-Token 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从通过 API 提交的表单发布数据成功.

但是在将 X-CSRF-TOKEN 添加到标头并设置 withCredentials: true 之后结果数据未发布到名为 insert.php

的脚本中

错误:

<块引用>

无法加载 安慰标题的值,未设置 Xsrf-Token.我应该如何设置 Xsrf-Token 值?

<小时>

更新:

 import {HttpClient, HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";构造函数(私有_http:HttpClient){}添加用户(信息){控制台日志(信息);//let headers = new Headers({ 'Content-Type': 'application/json' });//let options = new RequestOptions({ headers: headers, withCredentials: true });//console.log(options);return this._http.post("http://localhost/simple_api/insert.php",info).订阅(数据 =>{console.log("POST 请求成功", data);},错误 =>{console.log("错误", 错误);});}

app.module.ts

 import {HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";进口:[...HttpClient 模块,HttpClientXsrfModule.withOptions({cookieName: 'XSRF-TOKEN',headerName: 'X-CSRF-TOKEN'})],...

解决方案

将以下标题添加到您的 php 代码中

header("Access-Control-Allow-Credentials: true");

另外,为什么要混合使用旧的 HttpModule 和新的 HttpClient 模块?RequestOptionsHeaders 在 angular 6 中被弃用

如果使用HttpClient,内容类型已经默认设置为json,withCredentialsHttpClientXsrfModule设置.

您的请求可以简化为

 return this._http.post("http://localhost/simple_api/insert.php",info);

编辑HttpClientXsrfModule 在幕后创建的默认拦截器似乎无法处理绝对 url....

https://github.com/angular/angular/issues/18859

Posting data from the form submit via API was successful.

But after adding X-CSRF-TOKEN to the header and setting withCredentials: true resulted data were not posted to the script named insert.php

Error:

Failed to load http://localhost/simple_api/insert.php: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Removing withCredentials: true resulted data were successfully posted. But unable to see the X-CSRF-TOKEN

app.module.ts

import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import {HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";
import { UsrService } from './usr.service';
import { AppComponent } from './app.component';

@NgModule({
    declarations: [
      AppComponent,
      RegisterComponent,
      LoginComponent
    ],
    imports: [
      BrowserModule,
      FormsModule,
      HttpModule,
      AppRoutingModule,
      HttpClientModule,
      HttpClientXsrfModule.withOptions({
        cookieName: 'XSRF-TOKEN',
        headerName: 'X-CSRF-TOKEN'
      })
    ],
    providers: [UsrService],
    bootstrap: [AppComponent]
  })
  export class AppModule { }

user.services.ts

import { Http, Headers, RequestOptions, Response, URLSearchParams } from '@angular/http';
addUser(info){
    console.log(info);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, withCredentials: true });
    console.log(options);
    return this._http.post("http://localhost/simple_api/insert.php",info, options)
      .pipe(map(()=>""));
  }

insert.php

<?php
$data = json_decode(file_get_contents("php://input"));
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Access-Control-Allow-Headers: X-CSRF-Token, Origin, X-Requested-With, Content-Type, Accept");
?>

Consoling the values of the header, Xsrf-Token was not set. How am I supposed to set the Xsrf-Token values?


UPDATE:

import {HttpClient, HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";

constructor(private _http:HttpClient) { }

  addUser(info){
    console.log(info);
    // let headers = new Headers({ 'Content-Type': 'application/json' });
    // let options = new RequestOptions({ headers: headers, withCredentials: true });
    // console.log(options);
    return this._http.post("http://localhost/simple_api/insert.php",info)
        .subscribe(
                data => {
                    console.log("POST Request is successful ", data);
                },
                error => {
                    console.log("Error", error);
                }
            ); 
  }

app.module.ts

import {HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";

imports: [
    ...
    HttpClientModule,
    HttpClientXsrfModule.withOptions({
      cookieName: 'XSRF-TOKEN',
      headerName: 'X-CSRF-TOKEN'
    })
  ],
...

解决方案

Add the following header to your php code

header("Access-Control-Allow-Credentials: true");

Also, why are you mixing old HttpModule and new HttpClient module? RequestOptions and Headers are deprecated in angular 6

If you use HttpClient, content type is already set to json by default, and withCredentials is set by the HttpClientXsrfModule.

Your request can just be simplified to

 return this._http.post("http://localhost/simple_api/insert.php",info);

Edit The default interceptor created behind the scene by HttpClientXsrfModule does not seem to handle absolute urls....

https://github.com/angular/angular/issues/18859

这篇关于在 Angular 6 中添加 Xsrf-Token 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆