使用节点的request-promise将数据POST到JSON REST API


POST data to a JSON REST API using request-promise of node

PHP文件中获取$_POST数据时遇到问题。由于我的请求是发送后变量。

var rp = require('request-promise');
var options = {
    method: 'POST',
    uri: 'http://localhost/orangehrm_live/capacity-dashboard/getAllDetailsCapacity.php',
    headers: {
     'Content-Type': 'application/json; charset=utf-8',
     'Content-Length': dataString.length
     },
    body: {
        some: 'payload'
    },
    json: true // Automatically parses the JSON string in the response
};
rp(options)
    .then(function (repos) {
        console.log('User has %d repos', repos.length);
        if (repos) {
            res.send(repos);
        } else {
            res.sendStatus(404);
        }
    })
    .catch(function (err) {
        res.status(400).send(err);
    });

我的PHP文件包含以下代码。

<?php
class getAllDetailsCapacity{
    public function getChartRawData(){
        //$data = array('message' => 'HeLLO');

        $json = json_encode($_POST);
        print_r($json);
    }
}
function node_dispatch() {
        $obj=new getAllDetailsCapacity();
        if(isset($_POST)) {
            $obj->getChartRawData();
        }
        else {
            echo "You are in Admin Mode. Switch back to normal mode to serve your node app.";
        }
}
node_dispatch();
?> 

它在节点函数的请求体promise中显示else语句为未获取post值。

$_POST在包含键值对时接收POST正文。您需要将您想要的url编码在正文中的值POST到php。

HTTP请求可能如下所示:

POST /path/to/file.php HTTP/1.1
...
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
foo=bar&bar+baz=foo

只需添加表头并添加表单参数,而不是正文。您的数据会被发布到PHP文件中。

headers: {
            'content-type': 'application/x-www-form-urlencoded'
        },
        form: {
            some: dataString // Will be urlencoded
        },

content-type头告诉库如何将javascript对象转换为服务器期望的对象。它还告诉服务器来自客户端的数据的格式。

当您发送内容类型头application/json时,库会将您的请求转换为JSON。这将把正文转换为以下内容:{"some":"payload"}

当您发送内容类型标头application/x-www-form-urlencoded时,正文将转换为:some=payload