我试图在角度2中使用http发布数据,我添加了一个带有添加api的http调用,当我点击按钮时它应该将数据发布到我的数据库,在cosole中显示错误
XMLHttpRequest cannot load http://localhost/a2server/index.php/profile/addprofile.
Request header field Content-Type is not allowed by Access-Control-
Allow-Headers in preflight response.
EXCEPTION: Response with status: 200 Ok for URL: null
import {Component} from '@angular/core';
import {Http, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject } from 'rxjs/Subject';
@Component({
templateUrl: './components/http/http.html'
})
export class HttpSample {
http: Http;
postResponse = new Person();
constructor(http: Http) {
this.http = http;
}
onSubmit(){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost/a2server/index.php/profile/addprofile', JSON.stringify({firstName:'Joe',lastName:'Smith'}),{headers:headers})
.map((res: Response) => res.json())
.subscribe((res:Person) => this.postResponse = res);
}
}class Person{
firstName:string;
lastName:string;
}
并且我没有在我的视图中发布任何值,只是我放了一个按钮
<div>
<button (click)="postData()">Post Data</button>
</div>
答案 0 :(得分:0)
在服务器响应中添加Access-Control-Allow-Headers
标志。