码迷,mamicode.com
首页 > Web开发 > 详细

node初步一:HTTP请求

时间:2016-08-24 11:15:46      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

一、
创建pathtest.js文件
var http= require(‘http‘ );
var url= require(‘url‘ );
function start (){
       function onRequest(request ,response){
             var pathname =url .parse(request .url) .pathname ;// url.parse()解析请求头的url地址
             var query =url .parse(request .url) .query ;
            response .writeHead(200 ,{ ‘Content-Type‘ :‘text/plain; charset=utf-8‘}) ;
            response .write( "请求路径为:" +pathname +‘   ‘ );
            response .write( "请求参数为:" +query +‘   ‘ );

            response .write( "我是响应头的信息" );
            response .end() ;//响应结束
      }
      http .createServer(onRequest) .listen(9999) ;
      console .log( "服务器启动完成" );
}

start() ;

 

node pathtest.js
访问localhost:9999/star?id=1&name=cmf
页面内容如下:
请求路径为:/star   请求参数为:id=1&name=cmf   我是响应头的信息
 
二、
上面代码中
1、 http是require来的模块;url也是require来的模块;
2、http .createServer(onRequest) .listen(9999);是创建一个服务端口为9999;
3、createServer()传入一个方法,方法里面有两个参数一个是request(请求),response(响应);
4、request .url是请求地址可以用url模块里面的parse()方法来解析,解析成一个对象path;
5、被解析返回的对象(path)里面有query属性 返回请求参数
6、被解析返回的对象(path)里面有pathname属性 返回请求路径
技术分享

node初步一:HTTP请求

标签:

原文地址:http://www.cnblogs.com/yunyi1895/p/5801946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!