Node-http核心模块
使用http模块进行正向代理
const http = require("http");
const server = http.createServer()
server.on('request',(req,res)=>{
res.end('hello node')
})
// 正向代理,跨域获取猫眼的数据
let urlobj = {
hostname : 'm.maoyan.com',
method : 'GET',
port : 80,
path :'/ajax/comingList?ci=30&token=&limit=10'
}
// let str = 'http://m.maoyan.com/ajax/comingList?ci=30&token=&limit=10'
// 第一个参数一是一个请求的路径,可以是对象也可以是字符串
// 参数二是一个回调函数
http.request(urlobj,(response)=>{
let data = ''
response.on('data',(bf)=>{
data += bf
})
response.on('end',()=>{
console.log(data)
})
}).end()
//监听端口
server.listen(3000,(error)=>{
if(error){
console.log('ERROR : ',error)
}
});
正向代理 -- 案例二 西十区
// 跨域请求西十区的数据
http.request('http://m.xishiqu.com/ajax/home/index?cityCode=021',(res)=>{
let data = ''
res.on('data',(buffer)=>{
data += buffer
})
res.on('end',()=>{
console.log(' 西十区 - - - - - - - - - - - - - - - - - - - - - - - ')
console.log(data)
})
}).end()
使用http模块构建一个简易web服务
写法一 :
//引用模块 var http = require("http"); //创建一个服务器,回调函数表示接受到请求之后做的事情 var server = http.createServer(function(req,res){ //req参数表示请求,res表示响应 console.log("服务器接受到了请求"+req.url); //设置一个响应头 // res.writeHead(200,{"Content-Type":"text/plain;charset=UTF-8"});//纯文本
// res.writeHead(200,{"Content-Type":"text/html;charset=UTF-8"}); // 超文本会编译html标签
res.write("<h1>我是1标题</h1>");
res.write("<h2>我是2标题</h2>");
res.write("<h3>我是3标题</h3>");
res.write("<h4>我是4标题</h4>");
res.write("<h5>我是5标题</h5>");
res.write((1+2+3).toString());
res.end("<h1>我是一个主标题</h1>");
});
//监听端口
server.listen(3000,"127.0.0.1",(error)=>{
if(error){
console.log('ERROR : ',error)
}else{
console.log('服务启动成功!')
console.log('请访问: http://127.0.0.1:3000')
}
});
写法二 :
const http = require("http");
const server = http.createServer()
server.on('request',(req,res)=>{
res.end('hello node')
})
//监听端口
server.listen(3000,(error)=>{
if(error){
console.log('ERROR : ',error)
}else{
console.log('服务启动成功!')
console.log('请访问: http://localhost:3000')
}
});

浙公网安备 33010602011771号