简体   繁体   English

node.js POST请求

[英]node.js POST request

I looked at the api but I couldn't find it. 我看着api,但我找不到它。

Where/How should I put data on a POST request on client.request() or client.request("POST" ,...) ? 我应该如何/如何在client.request()client.request("POST" ,...)上的POST请求中放置数据?

Maybe you should look closer then. 也许你应该仔细看看。

This is straight from the node.js API documentation: 这可以直接来自node.js API文档:

request_headers is optional. request_headers是可选的。 Additional request headers might be added internally by Node. Node可能会在内部添加其他请求标头。 Returns a ClientRequest object. 返回ClientRequest对象。

Do remember to include the Content-Length header if you plan on sending a body. 如果您打算发送正文,请记住包含Content-Length标题。 If you plan on streaming the body, perhaps set Transfer-Encoding: chunked. 如果您计划流式传输正文,可能请设置Transfer-Encoding:chunked。

NOTE: the request is not complete. 注意:请求未完成。 This method only sends the header of the request. 此方法仅发送请求的标头。 One needs to call request.end() to finalize the request and retrieve the response. 需要调用request.end()来完成请求并检索响应。 (This sounds convoluted but it provides a chance for the user to stream a body to the server with request.write() .) (这听起来很复杂,但它为用户提供了使用request.write()将正文流式传输到服务器的机会。)

request.write() is for sending data. request.write()用于发送数据。

So you do it like this (more or less): 所以你这样做(或多或少):

var rq = client.request('POST', 'http://example.org/', {'Content-Length': '1024'});
var body = getMe1024BytesOfData();

rq.write(body);
rq.end();

This code is just here to get the concept across. 这段代码就是为了获得概念。 I have NOT tested it in any way. 我没有以任何方式测试它。

For more easier client requests you can use request module. 为了更容易的客户端请求,您可以使用请求模块。 It takes care of all the hard work and has a simple API. 它负责所有艰苦的工作,并有一个简单的API。

You can also use Requestify , a really cool and very simple HTTP client I wrote for nodeJS + it supports caching. 您还可以使用Requestify ,这是我为nodeJS +编写的非常酷且非常简单的HTTP客户端,它支持缓存。

Just do the following for executing a POST request: 只需执行以下操作即可执行POST请求:

var requestify = require('requestify');

requestify.post('http://example.com', {
    hello: 'world'
})
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)
    response.getBody();
});

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

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