一、http模块
- http.createSverver()
-
http是node自带的模块,通过
require("http")的方法载入; -
使用http创建服务器:
http.createServer(function(request,response){
response.writeHead(200,{"Content-Type":"text/plan"}); //设置返回头
response.write("this is test"); //返回的内容
response.end("end"); //响应结束
}).listen(2017); //设置端口
2.http.get(options[,callback]):发送请求,获取收据,通常不发送请求数据,可用于写爬虫.
-
options通常是个url;callback是回掉函数。
http.get("http://www.baidu.com/",function(response){
response.on("data",function(data){
// do somethiing
});
response.on("end",function(){
//do something
});
}).on("error",function(error){
console.log(error.message);
})
3.http.request(options[,callback]):发送请求,带请求数据,可用于灌水评论,伪装请求等操作
- options:共11个参数,常用的有5个
hostname:请求的地址,可用于
url.parse()方法得到,类似于www.imooc.com这种写法,不带之后的路径;port:端口;
path:以
/开头,通常是hostname 后面跟的路径,例如/course/docomment;method:通常是POST;
headers:是一个object,可以使用事先正常请求途径获得的response header;
-
callback:回掉函数,可以打印出请求的结构代码
res.statusCode和JSON.stringify(res.headers)请求头; -
最后需要将请求数据写道请求体里;最后收到结束请求;
var http = require("http"); var querystring = require("querystring"); var postData = querystring.stringify({ //key:value }); var options = { "hostname":"", "port":"", "path":"", "method":"", "headers":{} }; var req = http.request(options,function(res){ console.log("status:" +res.statusCode); console.log("headers:" +JSON.stringify(res.headers)); res.on("data",function(chunk){ //do something }); res.on("end",function(){ console.log("完成"); }) }); req.on("error",function(e){ console.log(e.message); }) req.write(postData); req.end();