javascript curl -d 等效于 Node.js http post 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23643802/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:17:45  来源:igfitidea点击:

curl -d equivalent in Node.js http post request

javascriptnode.jspostcurl

提问by Orlando

I know that the command

我知道命令

curl -X POST -d 'some data to send' http://somehost.com/api 

can be emulated in Node.js with some code like

可以在 Node.js 中使用一些代码来模拟

var http = require('http');
var post_data = 'some data to send',
    headers = {
        host: 'somehost.com',
        port: 80,
        method: 'POST',
        path: '/api',
        headers: {
            'Content-Length': Buffer.byteLength(post_data)
        }
    };

var request = http.request(headers, function(response) {
    response.on('data', function(d) {
        console.log(d);
    });
});
request.on('error', function(err) {
    console.log("An error ocurred!");
});
request.write(post_data));

request.end();

The question is because I'm looking for the equivalent in node of the cURL command

问题是因为我正在寻找 cURL 命令的节点中的等效项

curl -d name="Myname" -d email="[email protected]" -X POST http://somehost.com/api

how can i do that?

我怎样才能做到这一点?

This is because I wanna do a POST request to a Cherrypy server like this one, and I'm not able to complete the request.

这是因为我想向像这样Cherrypy 服务器发出 POST 请求,但我无法完成该请求。

EDITThe solution, as @mscdex said, was with the request library:

编辑正如@mscdex 所说,解决方案是使用请求库:

I've resolve the problem with the request library. My code for the solution is

我已经解决了请求库的问题。我的解决方案代码是

var request = require('request');

request.post('http://localhost:8080/api', {
  form: {
    nombre: 'orlando'
  }
}, function(err, res) {
  console.log(err, res);
});

Thank you!

谢谢!

回答by mscdex

You could encode it manually:

您可以手动对其进行编码:

var post_data = 'name=Myname&[email protected]';

Or you could use a module like requestto handle it for you (becomes especially nice if you have to upload files) since it will handle data escaping and other things for you.

或者你可以使用像request这样的模块来为你处理它(如果你必须上传文件会变得特别好),因为它会为你处理数据转义和其他事情。