【问题标题】:angular 2 http post issueangular 2 http post问题
【发布时间】:2017-12-07 09:19:13
【问题描述】:

当我尝试向我的服务器发送发布请求时出现错误
如何解决这个问题?

错误

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 邮政编码

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());
}
}

【问题讨论】:

  • 您还应该像这样添加允许标题: header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: *");
  • 浏览器发送预检请求,方法类型为OPTIONS,检查是否允许从不同域访问服务器。如果您在 php 中注入 header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");,作为对预检请求的响应,浏览器会理解可以进行进一步调用,并且它将获得对实际 GET/POST 调用的有效响应。

标签: php angular http-headers angular2-services


【解决方案1】:

在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;

【讨论】:

    猜你喜欢
    • 2018-07-28
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多