今天分享通過nodejs去請求一個外部鏈接痢缎。
主要很對get請求和post請求:
因?yàn)榫W(wǎng)站是http協(xié)議的,所以選擇的是:
const http = require('http')
http.request(options[, callback])
GET
// GET 請求
get(options) {
return new Promise((resolve,reject) => {
let body = '';
// 發(fā)出請求
let req = http.request(options,(res) => {
res.on('data',(data) => {// 監(jiān)聽數(shù)據(jù)
body += data;
}).on("end", () => {
console.log("HTTP DATA >>",body)
resolve(JSON.parse(body));
})
});
req.on("error",(e) => {
console.log("HTTP ERROR >>",e)
reject(e)
});
//記住世澜,用request一定要end独旷,如果不結(jié)束,程序會一直運(yùn)行寥裂。
req.end();
});
},
上面方法中的options
如下
let options = {
host: 'localhost',
port: '7002',
path: '/show',
method: 'GET',
headers:{
"Content-Type": 'application/json',
}
}
=======================================
POST
// POST請求
post(options,data) {
// let options = {
// host: 'localhost',
// port: '7002',
// path: '/update',
// method: 'POST',
// headers:{
// "Content-Type": 'application/json',
// "Content-Length": data.length
// }
// }
return new Promise((resolve,reject) => {
let body = '';
let req = http.request(options,(res) => {
res.on('data',(chuck) => {
body += chuck;
}).on('end', () => {
resolve(JSON.parse(body))
})
});
req.on('error',(e) => {
reject(e)
});
req.write(data);
req.end();
});
}
總結(jié):
可以把上面方法封裝在一個文件中嵌洼,方便調(diào)用