Node.js如何通过http调用外部接口
作者:CodingSlag
这篇文章主要介绍了Node.js如何通过http调用外部接口问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
node.js通过http调用外部接口
通过http.request发送带参数的post请求
data:发送的内容opt:描述将要发出的请求data:事件在数据到达时被触发end:请求结束时触发error:发生错误时被触发
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调用外部接口 使用request模块I(不推荐)
安装
npm install request
使用
const request = require('request');
//get请求 第一种
request('https://**********/gais/**/g**/**?name=2', function (err, response, body) {
//err 当前接口请求错误信息
//response 一般使用statusCode来获取接口的http的执行状态
//body 当前接口response返回的具体数据 返回的是一个jsonString类型的数据
//需要通过JSON.parse(body)来转换
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
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
