node服务开发实战---前后端交互的猜数字游戏

项目结构很简单:
项目结构
先上一下效果图:
node服务开发实战---前后端交互的猜数字游戏_第1张图片
从图中可以看到我们的前端界面是一个表单,点击按钮后会将输入框的数字通过ajax请求发到node后台,后台会根据接收到的参数来返回响应。

首先我们先来写一个简单的node服务吧 !
  • 项目初始化
    确保自己安装了node环境,新建一个文件夹:guessTheNumber。
    打开终端(CMD)在该文件夹下运行 npm init 初始化
    安装(自动重启服务器工具)nodemon:npm i nodemon -g (mac 下加sudo)

  • 编写node服务代码:新建index.js

    const http = require('http');
    http.createServer(function (req, res) {
    	res.end('hello node');
    }).listen(3000);
    console.log('server running on http://localhost:3000/');
    
  • 运行服务:nodemon index

  • 浏览器中访问:http://localhost:3000/ 可看到服务已经启动在这里插入图片描述
    这里返回的只是一个字符串,我们需要返回一个能发起请求的表单。用到了久违的JQ。

  • 新建index.html

    
    
    
      
      
      猜数字
      
    
    
      
    猜的数字(0~100):

    结果:

  • 使node服务可以返回一个html文档
    改变index.js代码,加入文件读取的一个库,将读取到的index.html的文件流直接返回到res中。

    const http = require('http');
    const fs = require('fs');
    http.createServer(function (req, res) {
    	fs.createReadStream(__dirname + '/index.html').pipe(res);
    }).listen(3000);
    

    重新访问http://localhost:3000/,得到一个表单
    node服务开发实战---前后端交互的猜数字游戏_第2张图片

接下来就是写后端的实现逻辑了
  • 当用户请求 ‘/’ 时我们返回首页内容
  • 当用户请求 ‘/guess’ 时,我们进行猜数字逻辑

猜数字的逻辑

  1. 随机产生一个0~100的随机数
  2. 等待用户访问,获取到用户输入的参数,对比参数
  3. 输出结果,如果猜对,重置随机数,重置猜的次数。否则随机数不变,猜的次数加1

实现代码如下:index.js

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

let randomNum = parseInt(Math.random() * 100);
let guessCount = 0;
console.log('randomNum', randomNum);
http.createServer(function (req, res) {
   const { pathname, query } = url.parse(req.url);
   if (pathname === '/') {
       fs.createReadStream(__dirname + '/index.html').pipe(res);
   }
   if (pathname === '/favicon.ico') {
       res.end();
       return
   }
   if (pathname === '/guess') {
       const guessNumber = Number(querystring.parse(query).guessNumber || -1);
       if (guessNumber !== -1) {
           guessCount++;
           if (randomNum === guessNumber) {
               res.end(`yes,猜了${guessCount}遍,数字已经重置!`);
               randomNum = parseInt(Math.random() * 100);
               guessCount = 0;
               console.log('randomNum', randomNum);
           }
           if (randomNum >= guessNumber) {
               res.end('too small');
           }
           if (randomNum <= guessNumber) {
               res.end('too big');
           }
       }
   }
}).listen(3000);
console.log('server running !');

代码中使用的一些模块

  • http:创建http服务
  • fs:读取文件
  • url:解析url
  • querystring:解析请求参数

再访问http://localhost:3000/ 就可以玩猜数字游戏了!
项目代码在这里猜数字源码,下一篇来实现一下express版本和koa版本,并对比一下其区别。

你可能感兴趣的:(node服务开发)