Node.js如何通過http調(diào)用外部接口
更新時間:2023年10月31日 17:22:16 作者:CodingSlag
這篇文章主要介紹了Node.js如何通過http調(diào)用外部接口問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
node.js通過http調(diào)用外部接口
通過http.request發(fā)送帶參數(shù)的post請求
data:發(fā)送的內(nèi)容opt:描述將要發(fā)出的請求data:事件在數(shù)據(jù)到達(dá)時被觸發(fā)end:請求結(jié)束時觸發(fā)error:發(fā)生錯誤時被觸發(fā)
var http = require("http");
var data = {username:"hello",password:"123456"};
data = JSON.stringify(data);
//data = require('querystring').stringify(data);
var opt = {
host:'localhost',
port:'8080',
method:'POST',
path:'/loginForeign.jspx',
headers:{
"Content-Type": 'application/json',
"Content-Length": data.length
}
}
var body = '';
var req = http.request(opt, function(res) {
console.log("response: " + res.statusCode);
res.on('data',function(data){
body += data;
}).on('end', function(){
console.log(body)
});
}).on('error', function(e) {
console.log("error: " + e.message);
})
req.write(data);
req.end();node.js調(diào)用外部接口 使用request模塊I(不推薦)
安裝
npm install request
使用
const request = require('request');
//get請求 第一種
request('https://**********/gais/**/g**/**?name=2', function (err, response, body) {
//err 當(dāng)前接口請求錯誤信息
//response 一般使用statusCode來獲取接口的http的執(zhí)行狀態(tài)
//body 當(dāng)前接口response返回的具體數(shù)據(jù) 返回的是一個jsonString類型的數(shù)據(jù)
//需要通過JSON.parse(body)來轉(zhuǎn)換
console.log(err, response, body);
if (!err && response.statusCode == 200) {
//todoJSON.parse(body)
var res = JSON.parse(body);
}
});
//get請求 第二種
request.get('https://**********/gais/**/g**/**?name=2',(err, response, body)=>{
console.log(err, response, body);
});
//get請求 第三種
request({
url: 'https://**********/gais/**/g**/**?name=2',
method: "GET",
json: true,
headers: {
"content-type": "application/json",
},
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // 請求成功的處理邏輯
}
});
//post請求
request({
url: 'https://**********/gais/**/g**/**',
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body:{
"frontendUuid": "121212",
"available": 0
}
}, (err, response, body) => {
console.log(err, response, body);
});官方文檔請查看:https://github.com/request/request
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
NodeJS感知和控制自身進(jìn)程的運行環(huán)境和狀態(tài)
NodeJS可以感知和控制自身進(jìn)程的運行環(huán)境和狀態(tài),也可以創(chuàng)建子進(jìn)程并與其協(xié)同工作,這使得NodeJS可以把多個程序組合在一起共同完成某項工作,并在其中充當(dāng)膠水和調(diào)度器的作用,和進(jìn)程管理相關(guān)的API單獨介紹起來比較枯燥,這里從一些典型的應(yīng)用場景出發(fā)2024-01-01
nodejs發(fā)布靜態(tài)https服務(wù)器的方法
這篇文章主要介紹了nodejs發(fā)布靜態(tài)https服務(wù)器的方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09

