gpt4 book ai didi

node.js - 如何使用 node-curl 发布数据?

转载 作者:搜寻专家 更新时间:2023-10-31 23:10:04 25 4
gpt4 key购买 nike

我对使用 node.js 的 LINUX 非常陌生。这只是我的第二天。我用 node-curl对于 curl 请求。在下面的链接中,我找到了带有 Get 请求的示例。谁能给我提供一个使用 node-curl 的 Post 请求示例。

https://github.com/jiangmiao/node-curl/blob/master/examples/low-level.js

最佳答案

您需要使用 setopt 来为 cURL 请求指定 POST 选项。您应该首先开始查看的选项是 CURLOPT_POSTCURLOPT_POSTFIELDS。来自libcurl documentationnode-curl 链接:

CURLOPT_POST

A parameter set to 1 tells the library to do a regular HTTP post. This will also make the library use a "Content-Type: application/x-www-form-urlencoded" header. (This is by far the most commonly used POST method).

Use one of CURLOPT_POSTFIELDS or CURLOPT_COPYPOSTFIELDS options to specify what data to post and CURLOPT_POSTFIELDSIZE or CURLOPT_POSTFIELDSIZE_LARGE to set the data size.

Optionally, you can provide data to POST using the CURLOPT_READFUNCTION and CURLOPT_READDATA options but then you must make sure to not set CURLOPT_POSTFIELDS to anything but NULL. When providing data with a callback, you must transmit it using chunked transfer-encoding or you must set the size of the data with the CURLOPT_POSTFIELDSIZE or CURLOPT_POSTFIELDSIZE_LARGE option. To enable chunked encoding, you simply pass in the appropriate Transfer-Encoding header, see the post-callback.c example.

CURLOPT_POSTFIELDS

... [this] should be the full data to post in a HTTP POST operation. You must make sure that the data is formatted the way you want the server to receive it. libcurl will not convert or encode it for you. Most web servers will assume this data to be url-encoded.

This POST is a normal application/x-www-form-urlencoded kind (and libcurl will set that Content-Type by default when this option is used), which is the most commonly used one by HTML forms. See also the CURLOPT_POST. Using CURLOPT_POSTFIELDS implies CURLOPT_POST.

If you want to do a zero-byte POST, you need to set CURLOPT_POSTFIELDSIZE explicitly to zero, as simply setting CURLOPT_POSTFIELDS to NULL or "" just effectively disables the sending of the specified string. libcurl will instead assume that you'll send the POST data using the read callback!


有了这些信息,您应该能够将以下选项添加到低级示例以使其发出 POST 请求:

var fieldsStr = '{}';
curl.setopt('CURLOPT_POST', 1); // true?
curl.setopt('CURLOPT_POSTFIELDS', fieldsStr);

您需要调整 fieldsStr 的内容以匹配服务器期望的格式。根据文档,您可能还需要对数据进行 url 编码——根据 this post,这应该与使用 encodeURIComponent 一样简单。 .

关于node.js - 如何使用 node-curl 发布数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15525057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com