如何使用 Http.post (Angular 2) (php 服务器端) 发布 json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41154319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to post json object with Http.post (Angular 2) (php server side)
提问by A. L
I'm trying to recreate Post JSON from angular 2 to phpbut it doesn't work as there's nothing in the $_REQUEST
variable on php side
我正在尝试从 angular 2 到 php重新创建Post JSON,但它不起作用,因为$_REQUEST
php 端的变量中没有任何内容
The code:
编码:
searchHttp({body}: any): Promise<any>
{
let headers = new Headers ({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers, method: "post" });
let test_this = {"search": "person"};
return this.http.post(this.post_url, JSON.stringify(test_this), options)
.toPromise()
.then(response =>
{
return response.text();
})
.catch(this.handleError);
}
Is there something I'm missing? I know that posts works with another format because I have that answered in another question.
有什么我想念的吗?我知道帖子适用于另一种格式,因为我在另一个问题中回答了这个问题。
Also, is http.request
better than http.post
?
另外,http.request
比http.post
?
Edit:
编辑:
After much consultation with Angular/Javascript experts, they believe this is a php issue. So anyone with knowledge of how to accept JSON objects on php side will be gladly welcomed.
在与 Angular/Javascript 专家进行多次协商后,他们认为这是一个 php 问题。因此,任何了解如何在 php 端接受 JSON 对象的人都会受到欢迎。
采纳答案by Amit kumar
angular 2 client side part
angular 2 客户端部分
ngOnInit() {
let body=Api+'product.php'+'?id=' + this.link_id;
this._callservice.callregister(body)
.subscribe( data => {
this.outputs=data;
},
error => console.log("Error HTTP Post"),
() => console.log("completed") );
}
}
call.service.ts
call.service.ts
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class AuthenticationService {
constructor(private _http:Http){}
postregister(api:any){
// console.log(api);
let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers, method: "post"});
return this._http.get(api,options)
.map(res => res.json())
.catch(this.handleError);
}
private handleError (error: Response) {
console.error(error);
return Observable.throw(error.json().error || ' error');
}
}
Server side PHP make sure on server side you have these three lines in php code.
服务器端 PHP 确保在服务器端你在 php 代码中有这三行。
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
Php file:
php文件:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
$servername = "localhost";
$username1 = "root";
$password = "root";
$dbname = "product";
$e=array("error"=>1,"message"=>"Account Already Exists");
$accountCreated = array( "error" =>0,
"data" => array(
"username" => "amit" ,
"password" => "anypassword",
"role"=> "user",
"id" => "anyid" ) );
// Create connection
$conn = mysqli_connect($servername, $username1, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$username = $_GET["username"];
$Pass = $_GET["password"];
$role= $_GET["role"];
$sql="SELECT COUNT(*) as user FROM users WHERE username = '$username'";
$result = mysqli_query($conn,$sql);
$line = mysqli_fetch_assoc($result);
$count = $line['user'];
if($count!=0)
{
echo json_encode($e);
}
else
{
$sql="INSERT INTO users(username,password,role)VALUES('$username','$Pass','$role')";
$result=mysqli_query($conn,$sql);
$sql="select * from users where username ='$username'";
$result=mysqli_query($conn,$sql);
$line=mysqli_fetch_assoc($result);
{
$accountCreated['data']['username']=$line['username'];
$accountCreated['data']['password']=$line['password'];
$accountCreated['data']['role']=$line['role'];
$accountCreated['data']['id']=$line['id'];
}
echo json_encode($accountCreated);
}
?>
i hope this will work for you .. for json i guess you should pass as options and use json decode for values you get in options.
我希望这对你有用..对于 json 我猜你应该作为选项传递并使用 json 解码你在选项中获得的值。
回答by Mitch
There doesn't appear to be anything wrong with the Angular code. The issue is in what the PHP is expecting to receive. I am not a PHP expert, but as you've mentioned that it works fine with jQuery, then that indicates that your PHP is expecting a URL-encoded value (as jQuery tends to work with that), not a JSON value.
Angular 代码似乎没有任何问题。问题在于 PHP 期望收到什么。我不是 PHP 专家,但正如您所提到的,它与 jQuery 一起工作得很好,那么这表明您的 PHP 需要一个 URL 编码的值(因为 jQuery 倾向于使用它),而不是一个 JSON 值。
In other words, what the server is trying to parse is:
换句话说,服务器试图解析的是:
search=person
What you are sending is:
您发送的是:
{ "search": "person" }
Try something more like the following to send it in the format you're wanting:
尝试更像以下内容以您想要的格式发送它:
let test_this = { "search": "person" };
let headers = new Headers ({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers, method: "post" });
http.post(this.post_url, test_this, options)