Alok
Alok

Reputation: 8978

POST request success on POSTMAN but not on Angular 7

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 :)

Upvotes: 2

Views: 5006

Answers (6)

Alok
Alok

Reputation: 8978

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.

Upvotes: 1

shrushti
shrushti

Reputation: 50

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.

Upvotes: 0

Aayushi Dassani
Aayushi Dassani

Reputation: 81

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


Upvotes: 0

Amin Shojaei
Amin Shojaei

Reputation: 6518

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

Upvotes: -1

coderman401
coderman401

Reputation: 582

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

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

Upvotes: 3

Adrita Sharma
Adrita Sharma

Reputation: 22213

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

Upvotes: 0

Related Questions