2017-10-10 44 views
0

我试图与角4 POST请求,使用此代码发送纬度和经度参数:如何使用Angular 4发布帖子请求?

let data = {lat: this.newLat, lng: this.newLng}; 

this.http.post(url, data) 
    .map(response => response.json()) 
    .subscribe(getResponse => console.log(getResponse)); 

在服务器端,我有以下的PHP代码片段:

header("Access-Control-Allow-Origin: *"); 
header("Access-Control-Allow-Headers: Content-Type"); 

if (isset($_POST['lat'], $_POST['lng'])) { 
    $response['msg'] = 'ok'; 
} else { 
    $response['msg'] = 'not ok'; 
} 
echo json_encode($response); 

不幸的是,服务器的响应始终是'not ok'。任何想法如何解决这个问题?所述$_POST变量始终是一个空数组

+0

任何JS错误...? – Farkie

+0

不,我得到“不好”的消息 –

+0

尝试'var_dump(file_get_contents(“php:// input”));'在PHP方面。看看你是否有任何POST参数。 – mega6382

回答

0

PHP超全球$_POST,只应该包装数据是application/x-www-form-urlencodedmultipart/form-data-encoded

但是,如果请求Content-Type是别的。您需要使用:

$post = file_get_contents('php://input'); 

欲了解更多信息看看这个答案:https://stackoverflow.com/a/8893792/2394254

0

参见the documentation

如果请求配置对象的数据属性包含一个对象,其序列化到JSON格式。

$ httpProvider.defaults.headers.post:(标题默认值POST请求) 内容类型:应用/ JSON


角是编码数据为JSON,而不是PHP自动解析为$_POST的数据格式之一。您需要登录parse JSON as described in this answer