使用 node.js 发送 Content-Type: application/json post

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

send Content-Type: application/json post with node.js

node.jspostcurl

提问by Radoslav

How can we make a HTTP request like this in NodeJS? Example or module appreciated.

我们如何在 NodeJS 中发出这样的 HTTP 请求?示例或模块表示赞赏。

curl https://www.googleapis.com/urlshortener/v1/url \
  -H 'Content-Type: application/json' \
  -d '{"longUrl": "http://www.google.com/"}'

回答by Josh Smith

Mikeal's requestmodule can do this easily:

Mikeal 的 request模块可以很容易地做到这一点:

var request = require('request');

var options = {
  uri: 'https://www.googleapis.com/urlshortener/v1/url',
  method: 'POST',
  json: {
    "longUrl": "http://www.google.com/"
  }
};

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body.id) // Print the shortened url.
  }
});

回答by Poonam Gupta

Simple Example

简单示例

var request = require('request');

//Custom Header pass
var headersOpt = {  
    "content-type": "application/json",
};
request(
        {
        method:'post',
        url:'https://www.googleapis.com/urlshortener/v1/url', 
        form: {name:'hello',age:25}, 
        headers: headersOpt,
        json: true,
    }, function (error, response, body) {  
        //Print the Response
        console.log(body);  
}); 

回答by JiN

As the official documentationsays:

正如官方文档所说:

body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.

body - PATCH、POST 和 PUT 请求的实体主体。必须是 Buffer、String 或 ReadStream。如果 json 为 true,则 body 必须是 JSON 可序列化对象。

When sending JSON you just have to put it in body of the option.

发送 JSON 时,您只需将其放在选项的正文中。

var options = {
    uri: 'https://myurl.com',
    method: 'POST',
    json: true,
    body: {'my_date' : 'json'}
}
request(options, myCallback)

回答by Paul T. Rawkeen

For some reason only this worked for me today. All other variants ended up in bad jsonerror from API.

出于某种原因,今天这对我有用。所有其他变体都以来自 API 的错误json错误告终。

Besides, yet another variant for creating required POST request with JSON payload.

此外,还有另一种使用 JSON 负载创建所需 POST 请求的变体。

request.post({
    uri: 'https://www.googleapis.com/urlshortener/v1/url',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({"longUrl": "http://www.google.com/"})
});