通过 API 从表单提交中发布数据是成功的。
但是在将 X-CSRF-TOKEN 添加到标头并设置 withCredentials: true
结果数据后没有发布到名为的脚本insert.php
错误:
加载http://localhost/simple_api/insert.php失败:对预检请求的响应未通过访问控制检查:响应中“Access-Control-Allow-Origin”标头的值不能是通配符“ *' 当请求的凭证模式是 'include' 时。因此,不允许访问源“ http://localhost:4200 ”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。
删除withCredentials: true
结果数据已成功发布。但看不到 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 { }
用户服务.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(()=>""));
}
插入.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");
?>
安慰标头的值,未设置 Xsrf-Token。我应该如何设置 Xsrf-Token 值?
更新:
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'
})
],
...