【问题标题】:send Content-Type: application/json post with node.js使用 node.js 发送 Content-Type: application/json post
【发布时间】:2012-01-30 08:00:17
【问题描述】:

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

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

【问题讨论】:

    标签: node.js post curl


    【解决方案1】:

    Mikeal's 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.
      }
    });
    

    【讨论】:

    • 感谢您提供这个有用的答案。最后,我意识到该选项有据可查。但迷失在许多其他人的中间......
    • 在我添加 headers: {'content-type' : 'application/json'}, 选项之前,它对我不起作用。
    • - 不推荐使用 NodeJs 的“请求”模块。 - 我们将如何使用“http”模块来做到这一点?谢谢。
    • Axios 更小更好:,查看this 帖子。
    【解决方案2】:

    简单示例

    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);  
    }); 
    

    【讨论】:

      【解决方案3】:

      正如official documentation 所说:

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

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

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

      【讨论】:

      • 只有我还是它的文档很烂?
      【解决方案4】:

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

      此外,还有另一种使用 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/"})
      });

      【讨论】:

        【解决方案5】:

        Axios 越来越小:

        const data = JSON.stringify({
          message: 'Hello World!'
        })
        
        const url = "https://localhost/WeatherAPI";
        
        axios({
            method: 'POST',
            url, 
            data: JSON.stringify(data), 
            headers:{'Content-Type': 'application/json; charset=utf-8'}
        }) 
          .then((res) => {
            console.log(`statusCode: ${res.status}`)
            console.log(res)
          })
          .catch((error) => {
            console.error(error)
          })
        

        同时查看在 Node.js 中发出 HTTP 请求的 5 种方法

        https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html

        参考:

        https://nodejs.dev/learn/make-an-http-post-request-using-nodejs

        https://flaviocopes.com/node-http-post/

        https://stackabuse.com/making-asynchronous-http-requests-in-javascript-with-axios/

        【讨论】:

          【解决方案6】:

          由于其他答案使用的request模块已被弃用,我可以建议切换到node-fetch

          const fetch = require("node-fetch")
          
          const url = "https://www.googleapis.com/urlshortener/v1/url"
          const payload = { longUrl: "http://www.google.com/" }
          
          const res = await fetch(url, {
            method: "post",
            body: JSON.stringify(payload),
            headers: { "Content-Type": "application/json" },
          })
          
          const { id } = await res.json()
          

          【讨论】:

            【解决方案7】:

            使用带有标题和帖子的请求。

            var options = {
                        headers: {
                              'Authorization': 'AccessKey ' + token,
                              'Content-Type' : 'application/json'
                        },
                        uri: 'https://myurl.com/param' + value',
                        method: 'POST',
                        json: {'key':'value'}
             };
                  
             request(options, function (err, httpResponse, body) {
                if (err){
                     console.log("Hubo un error", JSON.stringify(err));
                }
                //res.status(200).send("Correcto" + JSON.stringify(body));
             })
            

            【讨论】: