【发布时间】:2018-02-22 14:53:56
【问题描述】:
我正在尝试使用 HTTP POST 将单个对象从我的 angular 5 应用程序发送到 JSON 格式的 php API,但我无法让它工作。我知道这可能是非常基本的,但我是这个主题的新手,谷歌无法帮助我,或者我没有搜索正确的关键字。
错误:
1:在 data.service.ts 中带有 httpOptions 参数 -> http post 方法
2:data.service.ts 中没有 httpOptions 参数 -> http post 方法 php 文件中的第 55 行是这一行: $name=$_POST["name"];我也在文件中做了标记。
我不明白为什么在添加 Content-Type 标头时出现“405 不允许的方法错误”:application/json(错误 1)。如果我删除它,错误不会出现,但没有数据到达 API(错误 2)。
Content Type Header 在 API 的 php 文件中设置。 php文件中也允许POST方法。
我使用 Restlet 客户端测试了 API。它适用于 Content-Type: application/x-www-form-urlencoded 但也不适用于 application/json:
我做错了什么?
- Angular v5 -> package.json
- Angularapp -> localhost:4200
- API -> localhost:81 Apache
data.service.ts -> full File
const httpOptions = { headers: new HttpHeaders({ 'Content-Type':'application/json' })};
...
saveName(name: Name) {
const body = JSON.stringify(name.name);
return this.http.post('http://localhost:81/apitest/src/app/data/name.php', body, httpOptions);
}
API
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTION");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$connection = mysqli_connect('localhost', 'api', 'test', 'apitest');
$request_method = $_SERVER['REQUEST_METHOD'];
switch($request_method){
case 'GET':
if(!empty($_GET['nameId'])){
$nameId = intval($_GET['nameId']);
getNames($nameId);
} else {
getNames();
}
break;
case 'POST':
insertNames();
break;
case 'PUT':
updateNames();
break;
case 'DELETE':
deleteNames();
break;
default:
header('HTTP/1.0 405 Method Not Allowed');
break;
}
function insertNames()
{
global $connection;
$name=$_POST["name"]; // LINE 55 | Undefined index: name in [...] on line <b>55</b><br />
if(isset($_POST['name'])){
$query="INSERT INTO form SET name='{$name}'";
if(mysqli_query($connection, $query))
{
$response=array(
'status' => 201,
'status_message' =>'Name Added Successfully.'
);
}else
{
$response=array(
'status' => 400,
'status_message' =>'Name Addition Failed.'
);
}
}
else
{
$response=array(
'status' => 400,
'status_message' =>'Request Body Empty.'
);
}
header('Content-Type: application/json');
echo json_encode($response);
app.component.ts -> full File
saveName() {
this.dataService.saveName(this.name).subscribe(
data => {
this.getNames();
return true;
}, error => {
console.error('Failed');
}
);
}
HTML 表单
<html>
<head>
<title>API TEST</title>
</head>
<body>
<form action="data/name.php" method="POST">
<label for="name">Name: </label>
<input type="text" name="name" [(ngModel)]="name.name">
{{name.name}}
<button name="post" (click)="saveName()">post</button>
</form>
</body>
</html>
【问题讨论】:
标签: php angular typescript