nodejs使用http客戶端發送請求

這裏使用一個第三方模塊,needle,其使用方式比nodejs自帶的http模塊好用。

package.json依賴:

"dependencies": {
    "needle": "^2.5.0"
  }

使用方式:

在文件頭部引用模塊

const needle = require('needle')

GET請求

// 請求參數,json格式
const allParams = { name: 'jim' }
needle.request('GET',url, allParams, {
    // 設置header
    headers: {}
}, function(error, response) {
    // 成功
    if (!error && response.statusCode === 200) {
       console.log(response.body)
    }
});

needle.request()函數完整參數列表如下:

needle.request(method, url, data[, options][, callback])

  • method:請求方式,即GET,POST
  • url:請求url
  • data:請求參數
  • options:設置項,用來設置header等信息
  • callback:請求回調函數

POST表單提交

// 請求參數,json格式
const allParams = { name: 'jim' }
needle.request('POST',url, allParams, {
    // 設置header
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}, function(error, response) {
    // 成功
    if (!error && response.statusCode === 200) {
       console.log(response.body)
    }
});

POST發送JSON

// 請求參數,json格式
const allParams = { name: 'jim' }
needle.request('POST',url, allParams, {
    // 指定這一句即可
    json: true
}, function(error, response) {
    // 成功
    if (!error && response.statusCode === 200) {
       console.log(response.body)
    }
});

在配置項指定json: true,needle會認爲是發送json請求,自動設置header中的Content-Type爲application/json

POST 文件上傳

// 請求參數,json格式
const allParams = { 
    name: 'jim',// 普通表單參數
    // 上傳文件
    file1: { file: 'D:/aaa/bbb.txt', content_type: 'application/octet-stream' } 
    file2: { file: 'D:/aaa/ccc.png', content_type: 'application/octet-stream' } 
}
needle.request('POST',url, allParams, {
    // 指定這一句即可
    multipart: true
}, function(error, response) {
    // 成功
    if (!error && response.statusCode === 200) {
       console.log(response.body)
    }
});

在配置項指定multipart: true,表示需要上傳文件。

file1: { file: 'D:/aaa/bbb.txt', content_type: 'application/octet-stream' }

這部分是指定上傳的文件,其中file1表示上傳文件表單名稱,裏面的file表示文件路徑,後面的content_type可固定這麼寫。

以上四種請求方式已滿足大部分使用場景,更多使用方式參考:needle

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章