angular 2 http发布

时间:2017-07-04 04:04:43

标签: php angular http-headers angular2-services

我正在收到错误,当我尝试将邮件请求发送到我的服务器时如何解决此问题?

错误

  

XMLHttpRequest无法加载http://localhost/posttest.php。请求   标题字段不允许使用Content-Type   预检响应中的Access-Control-Allow-Headers。

php代码  http://localhost/posttest.php

header("Access-Control-Allow-Origin: *");<br>
$data = array("token"=>"","l_date"=>"");<br>
$data_json = json_encode($data);<br>
echo $data_json;

angular 2 http post code

import {Injectable} from '@angular/core';
import { Http, RequestOptions,Headers,Response } from '@angular/http';
import 'rxjs/add/operator/map'; 

@Injectable()
export class PostsService{
constructor(private http:Http){
    console.log("post service initialized ... ");

}
getPosts(id:number){
    return this.http.get('https://jsonplaceholder.typicode.com/posts/'+id).map(res=>res.json());
}
postexample(){
    var json=JSON.stringify({milla:"hi",login2:"milla"});
    var param="json="+json;
    let headers1 = new Headers({ 'Accept': 'application/json','Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers1 });
    let body = JSON.stringify(json);
    return this.http.post('http://localhost/posttest.php', body, options ).map((res: Response) => res.json());
}
}

1 个答案:

答案 0 :(得分:0)

在php中添加另一个访问控制头:

http://localhost/posttest.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$data = array("token"=>"","l_date"=>"");
$data_json = json_encode($data);
echo $data_json;