我已经关注了这个链接:Postman 'POST' request sucess but Angular 5 'Post' not working,并按照它来纠正我的问题,但有些问题没有得到解决。它总是给我else block
输出,我会在 Angular 代码中展示给你看。
注意:为 POSTMAN 完美工作。
可能的错误:我的 PHP 代码中存在无法识别输入的问题。
我的 API 是一个 POST API,它接受一个参数,即phone_num
,这是强制性的。从 Postman 传递参数适用于 api,但是当我通过 Angular 进行时,它不起作用并转到else block
API 代码。
由于这是一个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
是否在控制台中正确打印了数字,它正在控制台中传递,Network Console
在Chrome Dev
.
控制台中的错误日志:
任何帮助,将不胜感激。谢谢 :)