nodejs教程笔记(一)http模块 url模块

感谢b站教程:https://www.bilibili.com/video/av38925557?p=2

  1. 安装node snippets插件,可以进行代码补全
  2. 在vs code中输入node-,会有代码补全提示,选择node-http-server,会自动生成http代码。
  3. js的每一行代码后最好以’;'结尾。
  4. 控制台输出:
// 输出''内的字符串
console.log('Server running at http://127.0.0.1:8081/');
// 输出模式字符串,以${}来表示要填充的模式
// 此处的`位于键盘左上角,不是单引号' !!!!!!!!!!!!!!!!
console.log(`姓名:${getValue.name}--年龄:${getValue.age}`);
  1. 为了使页面输出的中文不乱码,需要同时将响应头编码和页面编码设置为支持中文的编码格式,如utf-8,注意响应头编码和页面编码需要保持一致。
  2. res.end()是结束响应的函数,不能忘记写,否则一直加载中,进入假死状态
  3. 在使用url、http模块的时候,需要先引入模块。
const http = require('http');
const url = require('url');
  1. 可通过url.parse(api, true)函数来解析url,得知传入的数据。通过url.parse(api, true).query可以得知请求的数据。

课程代码:

  1. 输入node-http-server自动补全的代码
// 引入http模块
var http = require('http');

// 创建服务
/* 
    request:获取url传递的信息
    response:给浏览器响应信息
*/
http.createServer(function (request, response) {
  // 设置响应头
  response.writeHead(200, {'Content-Type': 'text/plain'});
  // 在页面上输出并结束相应
  response.end('Hello World');
}).listen(8081); // 端口

console.log('Server running at http://127.0.0.1:8081/');
  1. http创建web服务并在网页上显示中文
// 为了不使其他人改该模块,故设置成const
const http = require('http');

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

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

    // 此处需要注意,响应头编码和页面编码需要保持一致!!!
    // 设置响应头
    // 状态码是200,文件类型是html,字符集是utf8
    // 解决乱码
    res.writeHead(200, {"Content-type":"text/html;charsets='utf-8'"});
    
    // 将html也设置成utf-8编码后即可输出中文
    // 内外不能同时为单引号或双引号!!!!
    // 解决乱码
    res.write("<head><meta charset='UTF-8'></head>");
    
    res.write('你好nodejs'); // 设置html编码前不认中文,中文输出乱码
    res.write('<h2>你好 nodejs</h2>');
    
    res.end(); // 结束响应,不要忘记写,否则一直加载中,假死状态

}).listen(3000);
  1. url模块的使用
const url=require('url');

var api='http://www.itying.com?name=zhangsan&age=20';

console.log(url.parse(api, true)); // 解析url,得知传入的数据

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

console.log(getValue);

// 输出模式字符串
console.log(`姓名:${getValue.name}--年龄:${getValue.age}`);
  1. 解析网页url的query
// 为了不使其他人改该模块,故设置成const
// 引入模块
const http = require('http');
const url = require('url');

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

    // 问号后面的值才能被query读取!!!!!!!
    // http://127.0.0.1?name=zhangsan&age=20 想获取url传过来的name和age

    // 此处需要注意,响应头编码和页面编码需要保持一致!!!
    // 设置响应头
    // 状态码是200,文件类型是html,字符集是utf8
    // 解决乱码
    res.writeHead(200, {"Content-type":"text/html;charsets='utf-8'"});
    
    // 将html也设置成utf-8编码后即可输出中文
    // 内外不能同时为单引号或双引号!!!!
    // 解决乱码
    res.write("<head><meta charset='UTF-8'></head>");
    
    // console.log(req.url); // 获取浏览器访问的地址

    if(req.url != '/favicon.ico') {
        var getValue = url.parse(req.url, true).query;
        console.log(`姓名:${getValue.name}--年龄:${getValue.age}`);
    }

    res.end('你好nodejs'); // 结束响应,不要忘记写,否则一直加载中,假死状态

}).listen(3000);
发布了219 篇原创文章 · 获赞 28 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Ema1997/article/details/104336939