2

I have followed this link: Postman 'POST' request sucess but Angular 5 'Post' not working, and have followed it to rectify my problem but some how it is not getting resolved. It always gives me else block output which I will show you in the Angular code itself.

Note: Working perfectly for POSTMAN.

Possible Error: There is a problem in my PHP code which is not been able to identify the input.

My API is a POST API, which accepts one param that is phone_num, which is mandatory. Passing the param from Postman works for the api, but when I do it by Angular, it doesn't work and goes to the else block of the API code.

Since this is a RAW PHP Code, so I don't know how to import this the microsoft.aspnet.webapi.cors package into my RAW PHP file, or will it fix this issue or not.

PHP Code:

<?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';
    }
?>

For POSTMAN, I get the phone_num showing up in the console/body. But for Angular, the console shows: No phone number found which is weird.

Angular Code:

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

I have also checked that this.customernum is printing the number correctly in the console, it is being passed in the console, checked in the Network Console of Chrome Dev.

Error Log in Console:

Error log message

Any help would be appreciated. Thanks :)

Alok
  • 8,452
  • 13
  • 55
  • 93

6 Answers6

3

you are using $_GET to retrieve your "POST" data

try $_POST['phone_num'] insted of $_GET['phone_num']

coderman401
  • 582
  • 3
  • 17
  • I am getting the same error, it is going on the else block everyt ime. Code was `if(isset($_POST['phone_num'])){ echo $_POST['phone_num'] }else { echo 'No number found'}` – Alok Jan 08 '20 at 06:42
  • then debug in code try: `print_r($request_method); exit;` and check why it is going on else block. I hope it will help – coderman401 Jan 08 '20 at 06:49
  • It's obviously `POST` in the console. I have checked it. My code is kinda correct, it is just that the information is not being taken from the Angular correctly, since **POSTMAN** implements the api right, and it works on it. Doing my code takes me into the `if block`, but using `$_POST` always pushes me to `else block` – Alok Jan 08 '20 at 06:53
1

I personally would like to thank two people for this, they are:

  • Nijeesh Joshy for sorting the biggest problem METHOD to METHOD contradiction with PHP script.
  • Brad for explaining the correct formatting for smooth functioning of the operation

Findings: For making this work like normal, that is $_POST working POST methods, you need to send the application/x-www-form-urlencoded Content-Type in your header. I don't know but sending out the data in Content-Type application/json just won't work.

Solutions:

1. SyntaxError: Unexpected token N => This was done because in the PHP script, it has to be returned in json_encode(), that is why it was returning this error in this statement No phone number found, N at 0th position in the else script.

<?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 not working for POST method from Angular code => Explained already FINDINGS above.

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

If you're still getting error, then would be some formatting errors in your angular code. Please follow this link. I hope that'd help you anyway. I saw people were very strict on using $_POST[] in place of $_GET[], but Content-Type was the problem.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Alok
  • 8,452
  • 13
  • 55
  • 93
0

Pass the raw object { 'phone_num': this.customernum }, don't use JSON.stringify()

Try like this:

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)
    );
  }
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
0

If you are using form than try to add value from that form directly instead of any extra variable. Replace form here by your form name

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` doesn't work in angular, we use `[(ngModel)]` and the data is definitely coming fine on the console. – Alok Jan 08 '20 at 07:02
  • If having form than can use either form or model, totally dependant on requirement. Try to use JSON.parse() instead of stringify.Here it is something related to data format – Aayushi Dassani Jan 08 '20 at 07:22
0

SyntaxError: Unexpected token N in JSON means you've got some malformed JSON, which is usually a string in there that's not wrapped in quotes.
1) Check if this.customernum is not empty or does not consist of any bad character.
2) Enclose phone_num in double-quotes.

shrushti
  • 50
  • 3
  • I have checked for both the points, **Not Empty, doesn't contain bad character, it is a string containing number**. Secondly, **putting phone number in double quotes doesn't help**. I have also tried this, `{ "phone_num": "xxxxxxxx"}`, doesn't help – Alok Jan 08 '20 at 07:05
  • Just add the key phone number in double quotes and not the value – shrushti Jan 08 '20 at 07:46
  • Not helping Error-404. Same error. The data is going null there, I don't know why – Alok Jan 08 '20 at 07:47
-1

you are getting phone-number from $_GET, so you should pass phone_num as query string

like this:

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

Postman will do this automatically for you in GET requests

Amin Shojaei
  • 5,451
  • 2
  • 38
  • 46