簡體   English   中英

如何在 node.js 中發出 GET 請求並發送正文?

[英]How to make a GET request in node.js sending a body?

我想知道如何在發送正文的 node.js 中發出 GET 請求。

   const options = {
        hostname: 'localhost',
        port: 3000,
        path: '/abc',
        method: 'GET'
    }

    http.get(options, (res) => {
        res.on('data', (chunk) => {
            console.log(String(chunk))
        })
    })

正如文檔中所說:

由於大多數請求是沒有主體的 GET 請求,因此 Node.js 提供了這種方便的方法。 此方法與http.request()的唯一區別在於它將方法設置為 GET 並自動調用req.end()

所以答案是直接使用http.request http.request有一個使用 POST 的示例,但它與 GET 相同(使用http.request開始請求,使用write發送正文數據,完成發送數據后使用end ),除了事實(如上所​​述) GET 通常沒有任何主體。 事實上, RFC 7231指出:

GET 請求消息中的負載沒有定義的語義; 在 GET 請求上發送有效負載正文可能會導致某些現有實現拒絕該請求。

使用標准http:

`const http = require('http');

https.get('http://localhost:3000/abc', (resp) => {

  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data).explanation);
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});`

希望這可以幫助

根本不建議在 GET 請求中使用 Body 因為它不是 HTTP 1.1 的建議行為,但您可以使用以下方法:

const data = JSON.stringify({
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
});


const https = require('https')

const options = {
  hostname: 'jsonplaceholder.typicode.com',
  port: 443,
  path: '/posts',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}

const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)

res.on('data', (d) => {
        process.stdout.write(d)
    })
})

req.on('error', (error) => {
  console.error(error)
})

req.write(data)
req.end()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM