【发布时间】: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 Dev 的Network Console 中检查。
控制台中的错误日志:
任何帮助将不胜感激。谢谢:)
【问题讨论】:
-
不要字符串化,只发送简单的对象。
-
您不需要使用 JSON.stringify。这是默认行为。
-
能不能加html sn-p,怎么输入customernum?
-
我会在这里告诉你@AayushiDassani
<input type="text" name='phoneForm' class="form-control" [(ngModel)]="customernum" placeholder="Please put in your number so that we can call you"> -
没有帮助@Mridul,发送到api的数据有一些问题,总是抛出
SyntaxError: Unexpected token B in JSON at position 0 at JSON.parse