【问题标题】:how to post data to php using nodejs如何使用nodejs将数据发布到php
【发布时间】:2017-06-10 11:29:13
【问题描述】:

我在php 中有一个处理$_POST 数据的函数。

使用 curl 我可以像这样发送我的数据:

curl --data "request=value2" http://localhost/mywebsite/

在 php 中:

if (isset($_POST)) {
                echo '<look>' . $_POST . '</look>';
                    exit;
            }

使用 curl 后,我可以在控制台中查看输出 &lt;look&gt;Array&lt;/look&gt;。

但是如何使用 node.js 调用上面的 post 请求

这是我迄今为止尝试过的:

const postData = querystring.stringify({
          'request': 'value2'
        });
        // the post options
        var optionspost = {
            host: 'localhost',
            path: 'mywebsite/?request=value2',
            method : 'POST',
            port : 80,
            headers: {
                 'Content-Type': 'application/x-www-form-urlencoded',
                 'Content-Length': Buffer.byteLength(postData)
            }
        };

        console.info('Options prepared:');
        //console.info(optionspost);
        console.info('Do the POST call');


        // do the POST call
        var reqPost = http.request(optionspost, function(res) {
            console.log("statusCode: ", res.statusCode);
            // uncomment it for header details
            //console.log("headers: ", res);
            res.on('data', function(d) {
                console.info('POST result:\n');
                console.log(d);
                var textChunk = d.toString('utf8');
                console.log(textChunk);
                console.info('\n\nPOST completed');
            });
        });

        // write the json data
        //reqPost.write(jsonObject);

        reqPost.on('error', function(e) {
            console.log("post error");
            console.error(e);
        });

        reqPost.write(postData);

        reqPost.end();

这是输出:

statusCode:  400
POST result:

<Buffer 3c 21 44 4f 43 54 59 50 45 20 48 54 4d 4c 20 50 55 42 4c 49 43 20 22 2d
2f 2f 49 45 54 46 2f 2f 44 54 44 20 48 54 4d 4c 20 32 2e 30 2f 2f 45 4e 22 3e .
. >
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.4.23 (Win64) PHP/5.6.25 Server at localhost Port 80</address>
</body></html>



POST completed

如何获得与 curl 相同的输出。请帮忙!

【问题讨论】:

    标签: php node.js curl


    【解决方案1】:

    或者,您也可以尝试使用 node-curl 包,它是 curl 命令的包装,这将是完成任务的更简单方法。

    在这里查看包裹。

    https://www.npmjs.com/package/node-curl

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-29
      • 2019-11-14
      • 2019-04-12
      • 1970-01-01
      相关资源
      最近更新 更多