从服务器主动发送请求
http.request(options[, callback])
获取百度首页信息:
导入模块:
const http = require('http');
const path = require('path');
const fs = require('fs');
options 请求内容信息:
let options = {
hostname : 'www.baidu.com',
port : 80
}
发送请求http.request(options[, callback]):
let req = http.request(options,(res)=>{
let info = '';
res.on('data',(chunk)=>{
info += chunk;
});
res.on('end',()=>{
fs.writeFile(path.join(__dirname,'baidu.html'),info,(err)=>{
console.log('已经获取到百度主页的内容');
});
});
});
表明请求的结束:
req.end();
测试后台接口(以前都是用的postman这个谷歌插件,模拟浏览器向服务器发送请求):
get请求:
导入模块:
const http = require('http');
options 请求内容信息:
let options = {
protocol : 'http:',
hostname : 'localhost',
port : 3000,
path : '/books'
}
发送请求http.request(options[, callback]):
let req = http.request(options,(res)=>{
let info = '';
res.on('data',(chunk)=>{
info += chunk;
});
res.on('end',()=>{
console.log(info);
});
});
表明请求的结束:
req.end();
post请求:
导入模块:
const http = require('http');
const querystring = require('querystring');
options 请求内容信息:
let options = {
protocol : 'http:',
hostname : 'localhost',
port : 3000,
path : '/books/book',
method : 'post',
headers : {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
发送请求http.request(options[, callback]):
let req = http.request(options,(res)=>{
let info = '';
res.on('data',(chunk)=>{
info += chunk;
});
res.on('end',()=>{
console.log(info);
});
});
将数据写入到请求主体:
let data = querystring.stringify({
name : 'adafa',
author : 'asdfa',
category : 'afdasf',
description : 'adsfa'
});
req.write(data);
表明请求的结束:
req.end();