http是nodejs中一个非常重要的内置模块,用于开发http服务器和web应用程序。
创建一个http服务非常简单。
04_http.js
//04 http 介绍 //引入http 模块 var http=require("http"); //创建http服务器实例 var server =http.createServer(function (req,res) { res.writeHead(200,{'content-type':'text/html;charset=utf-8'}); res.end("你好nodejs"); }); //监听本地端口 3000 server.listen(3000); console.log("nodejs server run at 3000");
05_http_url_get.js
//05 http url get //介绍 req 和res对象 、 url模块 、获取http get参数 var http=require("http"); var url=require("url"); var server =http.createServer(function (req,res) { var reqUrl = req.url; if(reqUrl=='/favicon.ico'){//忽略 ico小图标 return ; } console.log(reqUrl); //使用url模块 解析req.url 得到一个urlObj 对象 var urlObj= url.parse(reqUrl,true); console.log(urlObj); res.writeHead(200,{'content-type':'text/html;charset=utf-8'}); res.write('请求url: '+reqUrl+'<br/>'); res.write('pathname: '+urlObj.pathname+'<br/>'); //requestPage res.write('get参数name: '+urlObj.query['name']+'<br/>'); //get 请求参数 res.write('get参数age: '+urlObj.query['age']+'<br/>');//get请求参数 res.write('search: '+urlObj.search+'<br/>'); //查询字符串 ?name=zhangsan&age=22 // 浏览器输入 http://localhost:3000/about?name=zhangsan&age=22 //urlObj 对象如下 // Url { // protocol: null, // slashes: null, // auth: null, // host: null, // port: null, // hostname: null, // hash: null, // search: '?name=zhangsan&age=22', // query: { name: 'zhangsan', age: '22' }, // pathname: '/about', // path: '/about?name=zhangsan&age=22', // href: '/about?name=zhangsan&age=22' } res.end();//结束响应 }); server.listen(3000); console.log('nodejs server run at 3000');
Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1