0
我越来越错误,当我试图发送请求到我的服务器
如何解决这个问题?角2 http帖子
错误
的XMLHttpRequest不能加载http://localhost/posttest.php。请求 标头字段内容类型不允许通过 预检响应中的访问控制允许标题。
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;
角2 HTTP POST码
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());
}
}
你还应该添加这样的allow-headers:header(“Access-Control-Allow-Origin:*”); header(“Access-Control-Allow-Headers:*”); –
浏览器发送一个预检请求,其方法类型为“OPTIONS”,以检查是否允许从不同的域访问服务器。为响应预检请求,如果您注入了 报头(“Access-Control-Allow-Headers”,“Access-Control-Allow-Headers,Origin,Accept,X-Requested-With,Content-Type,Access-请求方法,访问控制请求头“);'在你的php 浏览器明白,进行进一步的调用是可以的,它会得到对实际的GET/POST调用的有效响应。 – crowchirp