【问题标题】:POST request success on POSTMAN but not on Angular 7POSTMAN 上的 POST 请求成功,但 Angular 7 上没有
【发布时间】:2020-04-25 16:06:30
【问题描述】:

我已关注此链接:Postman 'POST' request sucess but Angular 5 'Post' not working,并已关注它来纠正我的问题,但有些问题没有得到解决。它总是给我else block 输出,我将在 Angular 代码中向您展示。

注意:非常适合 POSTMAN。

可能的错误:我的 PHP 代码中存在无法识别输入的问题。

我的 API 是一个 POST API,它接受一个参数 phone_num,这是强制性的。从 Postman 传递参数适用于 api,但是当我通过 Angular 进行时,它不起作用并转到 API 代码的 else block

由于这是一个RAW PHP代码,所以我不知道如何将这个microsoft.aspnet.webapi.cors包导入到我的RAW PHP文件中,或者它是否会解决这个问题。

PHP 代码:

<?php
    include('/Applications/MAMP/htdocs/api/Requests/library/Requests.php');
    $request_method = $_SERVER['REQUEST_METHOD'];

    if ( $request_method == 'POST' ){
            if(isset($_GET['phone_num'])){
               echo $_GET['phone_num'];
            }else{
              echo 'No phone number found';
            }
    }else {
        echo 'No defined function for this method. Please use POST only';
    }
?>

对于 POSTMAN,我在控制台/正文中显示了 phone_num。但是对于 Angular,控制台显示:No phone number found,这很奇怪。

角度代码:

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

export class AppComponent {
  message: string;
  url: string = 'xxxxxxx';
  customernum: number;
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',

    })
  };

  constructor(private http: HttpClient){}

  callMe(){
    this.message = 'Please wait....'
    this.http.post(this.url, JSON.stringify({ 'phone_num': this.customernum }), this.httpOptions).subscribe(
      response => console.log(JSON.stringify(response)),
      error => console.log(error)
    );
  }
}

我还检查了this.customernum 是否在控制台中正确打印数字,它正在控制台中传递,在Chrome DevNetwork Console 中检查。

控制台中的错误日志:

任何帮助将不胜感激。谢谢:)

【问题讨论】:

  • 不要字符串化,只发送简单的对象。
  • 您不需要使用 JSON.stringify。这是默认行为。
  • 能不能加html sn-p,怎么输入customernum?
  • 我会在这里告诉你@AayushiDassani &lt;input type="text" name='phoneForm' class="form-control" [(ngModel)]="customernum" placeholder="Please put in your number so that we can call you"&gt;
  • 没有帮助@Mridul,发送到api的数据有一些问题,总是抛出SyntaxError: Unexpected token B in JSON at position 0 at JSON.parse

标签: php angular api


【解决方案1】:

传递原始对象{ 'phone_num': this.customernum },不要使用JSON.stringify()

试试这样:

callMe(){
    this.message = 'Please wait....'
    this.http.post(this.url, { 'phone_num': this.customernum }, this.httpOptions).subscribe(
      response => console.log(JSON.stringify(response)),
      error => console.log(error)
    );
  }

【讨论】:

  • 没有区别阿德里塔,同样的错误。无论如何感谢您的帮助
【解决方案2】:

您正在使用 $_GET 检索您的“POST”数据

尝试$_POST['phone_num'] insted of $_GET['phone_num']

【讨论】:

  • 我遇到了同样的错误,它每次都在 else 块上。代码是if(isset($_POST['phone_num'])){ echo $_POST['phone_num'] }else { echo 'No number found'}
  • 然后在代码中调试尝试:print_r($request_method); exit; 并检查它为什么会出现 else 块。我希望它会有所帮助
  • 控制台中明显是POST。我已经检查过了。我的代码有点正确,只是信息没有正确地从 Angular 中获取,因为 POSTMAN 实现了 api 权利,并且可以在上面运行。执行我的代码将我带入if block,但使用$_POST 总是将我推向else block
【解决方案3】:

您从$_GET 获得phone-number,因此您应该将phone_num 传递为query string

像这样:

http://example.com/blablabla?phone_num=0123456789

邮递员会在 GET 请求中自动为您执行此操作

【讨论】:

    【解决方案4】:

    如果您使用的是表单,请尝试直接从该表单添加值,而不是任何额外的变量。将此处的表单替换为您的表单名称

    this.http.post(this.url, { 'phone_num': this.form.value.phoneForm}, this.httpOptions).subscribe(
          response => console.log(JSON.stringify(response)),
          error => console.log(error)
        );
    
    
    

    【讨论】:

    • this.form.value.phoneForm 在 Angular 中不起作用,我们使用 [(ngModel)] 并且控制台上的数据肯定会正常。
    • 如果有表格,可以使用表格或模型,完全取决于要求。尝试使用 JSON.parse() 而不是 stringify。这​​里是与数据格式有关的东西
    【解决方案5】:

    SyntaxError: Unexpected token N in JSON 意味着你有一些格式错误的 JSON,它通常是一个没有用引号括起来的字符串。
    1) 检查 this.customernum 是否不为空或不包含任何错误字符。
    2) 用双引号将 phone_num 括起来。

    【讨论】:

    • 我已经检查了这两个点,Not Empty,不包含坏字符,它是一个包含数字的字符串。其次,将电话号码放在双引号中没有帮助。我也试过这个,{ "phone_num": "xxxxxxxx"},没有帮助
    • 只需在双引号中添加关键电话号码而不是值
    • 没有帮助 Error-404。同样的错误。那里的数据为空,我不知道为什么
    【解决方案6】:

    我个人要感谢两个人,他们是:

    • Nijeesh Joshy 用于排序最大的问题 METHOD to METHOD 与 PHP 脚本的矛盾。
    • Brad 用于解释正确的格式以使操作顺利运行

    调查结果:为了使这项工作正常进行,即$_POST 工作 POST 方法,您需要将 application/x-www-form-urlencoded Content-Type 发送到您的标题。我不知道,但是以 Content-Type application/json 发送数据是行不通的。

    解决方案:

    1. SyntaxError: Unexpected token N => 这样做是因为在 PHP 脚本中,它必须在 json_encode() 中返回,这就是为什么它在 else 脚本中的语句 No phone number found, N at 0th position 中返回此错误。

    <?php
        include('/Applications/MAMP/htdocs/api/Requests/library/Requests.php');
        $request_method = $_SERVER['REQUEST_METHOD'];
    
        if ( $request_method == 'POST' ){
                if(isset($_POST['phone_num'])){
                   echo $_POST['phone_num'];
                }else{
                  echo json_encode('No phone number found');
                }
        }else {
            echo json_encode('No defined function for this method. Please use POST only');
        }
    ?>
    

    2。 $_POST 不适用于 Angular 代码中的 POST 方法 => 上面已经解释了发现。

    import { Component } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    
    export class AppComponent {
      message: string;
      url: string = 'xxxxxxx';
      customernum: number;
      httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/x-www-form-urlencoded'
        })
      };
    
      body: any = `phone_num=${this.customernum}`;  
    
      constructor(private http: HttpClient){}
    
      callMe(){
        this.message = 'Please wait....'
        this.http.post(this.url, this.body, this.httpOptions).subscribe(
          response => console.log(JSON.stringify(response)),
          error => console.log(error)
        );
      }
    }
    

    如果您仍然遇到错误,那么您的角度代码中会出现一些格式错误。请关注this 链接。我希望这对你有帮助。我看到人们对使用$_POST[] in place of $_GET[] 非常严格,但Content-Type 是问题所在。

    【讨论】:

      猜你喜欢
      • 2020-05-26
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 2020-08-02
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      相关资源
      最近更新 更多