繁体   English   中英

使用节点的请求承诺将数据发布到 JSON REST API

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

我在PHP文件中获取$_POST数据时遇到问题。 因为我的请求是发送 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();
?> 

它显示 else 语句,因为它没有在节点函数的请求承诺正文中获得 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

只需添加标题并添加表单参数而不是 body 。 您的数据将发布到 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM