Node.js基础学习(1)

 1 //用于创建网站服务器的模块
 2 const http = require('http');
 3 //app对象就是网站服务器对象
 4 const app = http.createServer();
 5 // node内置对象 用于处理URL地址
 6 const url = require('url');
 7 
 8 //事件(请求)处理函数,当客户端有请求的时候
 9 //request请求,response响应
10 app.on('request',(req,res)=>{
11     //获取请求的方式
12     //req.method
13     // console.log(req.method);    
14 
15     //获取请求的地址
16     //req.url
17     console.log(req.url);
18     //第一个参数要解析的url地址,第二个参数为true时 解析当前请求地址已对象的形式返回 
19     // console.log(url.parse(req.url,true).query);
20 
21     // req.headers
22     // console.log(req.headers['accept']); 
23 
24     // 用解构赋值的形式拿到当前url里面的query,pathname
25     let {query,pathname}=url.parse(req.url,true);
26     console.log(query.name);
27     console.log(query.age);
28 
29 
30     res.writeHead(200, {
31         'content-type': 'text/html;charset=utf8'
32     });
33     
34    
35     if(pathname=='/index' || pathname=='/' ){
36         res.end('<h2>welcome to homepage</h2>');
37     }else if(pathname=='/list'){
38         res.end('welcome to listpage');
39     }else{
40         res.end('404');
41     }
42     
43 
44     // if(req.method== 'POST'){
45     //     res.end('post');
46     // }else if (req.method== 'GET'){
47     //     res.end('get');
48     // }
49     //响应内容
50     // res.end('<h2>hello user</h2>')
51 
52 });
53 
54 //监听端口
55 app.listen(3000);
56 console.log('网站服务启动成功!')
57 
58 // 访问本地 localhost:3000

 

posted @ 2020-10-31 02:10  铁马冰河入_来  阅读(103)  评论(0编辑  收藏  举报