本文源于实践及其部分网络搜索:
其实大部分,官方都有介绍...
官方参考链接:https://nodejs.org/api/http.html
var http = require('http');
var querystring = require('querystring');
var options = {
host: '127.0.0.1', // 请求地址 域名,google.com等..
port:80,
path:path, // 具体路径eg:/upload
method: 'GET', // 请求方式, 这里以post为例
headers: { // 必选信息, 可以抓包工看一下
'Content-Type': 'application/json'
}
};
http.get(options, function(res) {
var resData = "";
res.on("data",function(data){
resData += data;
});
res.on("end", function() {
callback(null,JSON.parse(resData));
});
})
(2):post 请求:
var postData = querystring.stringify({
'msg' : 'Hello World!'
});var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};var req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});// write data to request bodyreq.write(postData);req.end();
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
res.on('end',function(chunk){
console.log("body: " + chunk);
})
});
参考链接:https://nodejs.org/api/http.html
/m1=ff&op=get