Node中的Http模块和Url模块的使用

场景

如果我们编写后端的代码时,需要Apache 或者Nginx 的HTTP 服务器,
来处理客户端的请求相应。不过对Node.js 来说,概念完全不一样了。使用Node.js 时,
我们不仅仅在实现一个应用,同时还实现了整个HTTP 服务器。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

有了node,我们任何一个js 文件,都可以通过node 来运行。也就是说,node 就是一个js 的执行环境。

Node.js 中,将很多的功能,划分为了一个个module(模块)。Node.js 中的很多功能都是通过模块实现。

HTTP模块的使用

首先新建一个目录,再次目录下新建app.js

const http = require('http');

/*
    req   获取客户端传过来的信息
    res  给浏览器响应信息
*/

http.createServer((req,res)= >{

    console.log(req.url);  //获取url

    //设置响应头
    //状态码是 200,文件类型是 html,字符集是 utf-8
    res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"}); //解决乱码

    res.write("<head> <meta charset='UTF-8'></head>");  //解决乱码

    res.write('公众号:霸道的程序猿');

    res.write('<h2>公众号:霸道的程序猿</h2>');

    res.end();  //结束响应

}).listen(3000);

然后在此目录下打开cmd

node app.js

这样一个简单的http创建web服务就实现了。

打开浏览器,输入

http://localhost:3000/

URL模块的使用

首先通过

const url=require('url');

引入url模块

url.parse

解析url

怎样获取请求的参数

在目录下新建url.js

const url=require('url');

var api='https://blog.csdn.net/BADAO_LIUMANG_QIZHI?name=zhangsan&age=20';

 

console.log(url.parse(api,true));

var getValue=url.parse(api,true).query;

console.log(getValue);

console.log(`姓名:${getValue.name}--年龄:${getValue.age}`);

然后在终端中输入

node url.js

Http模块与URL模块结合使用

在目录下新建httpUrl.js

const http =require('http');
const url =require('url');

/*
    req   获取客户端传过来的信息
    res  给浏览器响应信息
*/

http.createServer((req,res)=>{

    //http://localhost:3000/?name=badao&age=24  想获取url传过来的name 和age

    //设置响应头
    //状态码是 200,文件类型是 html,字符集是 utf-8
    res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"}); //解决乱码

    res.write("<head> <meta charset='UTF-8'></head>");  //解决乱码   

    console.log(req.url);   //获取浏览器访问的地址

    if(req.url!='/favicon.ico'){

        var userinfo=url.parse(req.url,true).query;
        
        console.log(`姓名:${userinfo.name}--年龄:${userinfo.age}`);
    }

    res.end('你好nodejs');  //结束响应

}).listen(3000);

然后打开终端输入:

node httpUrl.js

打开浏览器输入:

http://localhost:3000/?name=badao&age=24

猜你喜欢

转载自www.cnblogs.com/badaoliumangqizhi/p/13401190.html