我正在使用angular 2,我正在尝试通过post请求将数据从angular发送到我服务器上的php文件。当我尝试时,我收到此错误“SyntaxError:UENpected token< in JSON in position 0”。这是我到目前为止的代码。任何援助将不胜感激。谢谢!
应用组件按钮
<button class="btn btn-primary btn-lg" (click)="postData()"> Make Post Request </button>
应用程序组件代码我使用此功能并在模板中的按钮上调用它以发送请求
postData(){
this.requestService.postSomeData()
.subscribe(
data => this.postRequest = data,
error => console.log('There is an error: ' + error),
() => console.log("Completed Post Request!")
);
}
请求服务代码 - 这是我在应用程序组件中调用的服务
postSomeData(){
let url = 'link to php file here';
let jsonData = {
name: 'my Name'
};
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post(url, jsonData, {headers: headers})
.map(res => res.json());
}
PHP文件
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
echo "Name: ".$name;
?>
答案 0 :(得分:0)
问题来自于PHP(服务器端我假设)没有返回响应。