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:
Any help would be appreciated. Thanks :)