本文源於實踐及其部分網絡搜索:javascript
其實大部分,官方都有介紹...php
官方參考連接: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));
});
})
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 body
req.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