【问题标题】:Angular2 http.post won't send JSON data to APIAngular2 http.post 不会将 JSON 数据发送到 API
【发布时间】:2017-09-01 13:25:00
【问题描述】:

我已经尝试了将近一天的时间来解决这个问题,但没有运气。 我有一个简单的http.post 请求:

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

  @Component({
    selector: 'SendPost',
  })
  export class SendPostComponent {

    constructor(
        private http:Http,
    ) {}

    private urlPost:string = 'www.mydomain.com/api/order.php'

    private addToBasket() {
      var data = {
        foo: "bar",
        foo1: "another"
      }
        var postData = JSON.stringify(data);

        let headers = new Headers({'Content-Type': 'application/json'}); //x-www-form-urlencoded
        headers.append('Access-Control-Allow-Methods', "GET, POST, OPTIONS");
      let options = new RequestOptions({ headers: headers });

      this.http.post(
            this.urlPost, 
            postData, 
            options
        )
        .toPromise()
                .then((res) => {this.extractData(res)});
    }       

    private extractData(res: Response) {
        console.log('extractData:', res);
    }

  }

我将 API 端点剥离到绝对最小值:没有 .htacces,只有 php 文件这个简单的代码:

<?php print_r(json_encode($_REQUEST)); die; ?>

我不断得到一个空数组作为回报。但是,如果我像这样更改代码:

var data2 = 'foo=bar&foo1=another'
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });

然后 $_REQUEST 对象获取我的数据。我错过了什么?

【问题讨论】:

  • 如果你得到带有 URL 参数的结果,那么它是 php 相关的,而不是 angular 相关的!我不熟悉 PHP,但也许你应该将其设置为接受 JSON 发布请求
  • JSON.stringify 将返回一个 json 字符串,但您需要的是 stackoverflow.com/questions/1714786/…

标签: php json angular


【解决方案1】:

PHP $_REQUEST 是:

一个关联数组,默认包含 $_GET、$_POST 和 $_COOKIE 的内容

$_POST

在请求中使用 application/x-www-form-urlencoded 或 multipart/form-data 作为 HTTP Content-Type 时,通过 HTTP POST 方法传递给当前脚本的变量关联数组。

PHP 无法解析“application/json”数据,解决方法是php wrapper,通过使用“file_get_contents('php://input')”可以通过这种方式从请求实体中获取数据:

$body = file_get_contents('php://input');
$data = json_decode($body);
print_r($data);  // here is what you need

【讨论】:

    猜你喜欢
    • 2013-10-15
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2017-04-30
    • 2017-07-05
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多