Node基本使用

本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2021-07-03

功能:

/user?act=reg&user=aaa&pass=123456 : 接口:注册

/user?act=login&user=aaa&pass=123456: 接口:登录

/a.html :获取静态资源,从./www文件夹中读取,有就返回,没有就返回404。

const http = require('http');
const fs = require('fs');
const urlLib = require('url');
const queryString = require('querystring');

var users = {}

http.createServer((req, res) => {
  // write输出中文时,能够正常显示
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  // GET
  var obj = urlLib.parse(req.url, true);
  var url = obj.pathname;
  const GET = obj.query;

  // POST
  var str = '';
  req.on('data', data => {
    str += data;
  })

  req.on('end', () => {
    const POST = queryString.parse(str);
    console.log(POST);
  })

  if (url == '/user') {
    // 接口请求
    switch(GET.act) {
      // 注册
      case 'reg':
        if (users[GET.user]) {
          res.write('{"ok": false, "message": "用户名已存在"}');
        } else {
          // 记录在users中
          users[GET.user] = GET.pass;
          res.write('{"ok": true, "message": "注册成功"}');
        }
        break;
      // 登录
      case 'login':
        if (!users[GET.user]) {
          res.write('{"ok": false, "message": "此用户不存在"}');
        } else if (users[GET.user] == GET.pass) {
          res.write('{"ok": true, "message": "登录成功"}');
        } else {
          res.write('{"ok": false, "message": "密码错误"}');
        }
        break
      default:
        res.write('{"ok": false, "message": "未知功能"}');
    }
    res.end();
  } else {
    // 文件请求 
    var file_path = './www' + url;
    fs.readFile(file_path, (err, data) => {
      if (err) {
        res.write('404');
      } else {
        res.write(data);
      }
      res.end();
    })
  }

  // 对接口的访问
}).listen(3000);