node 實現簡單的數據交互入門

註冊登錄的html 代碼簡單 就不一一講訴了 直接貼代碼javascript

用戶名:<input id="username" type="text" name='username' />
    <br/>
    密  碼:<input id="password" type="password" name='pswd' />
    <br/>
    <input id="register" type="submit" value="註冊" />
    <input id="login" type="submit" value="登錄" />
複製代碼

登錄頁面的javascripthtml

window.onload = function(){
        var $username = document.getElementById('username'),
            $password = document.getElementById('password'),
            $login = document.getElementById('login'),
            $register = document.getElementById('register');
        $login.addEventListener('click',function(){
          var uservalue = $username.value;
          var password =  $password.value;
          if (!!uservalue && !!$password) {
            var xhr = new XMLHttpRequest();
            xhr.open('post','http://localhost:8080/login');
            xhr.send(`username=${uservalue}&password=${password}`);
            xhr.onreadystatechange = function() {
              if (xhr.readyState === 4 && xhr.status === 200 ) {
                //邏輯處理
              }
            }
          } 
        })
        $register.addEventListener('click',function(){
          var uservalue = $username.value;
          var password =  $password.value;
          if (!!uservalue && !!$password) {
            var xhr = new XMLHttpRequest();
            xhr.open('post','http://localhost:8080/register');
            xhr.send(`username=${uservalue}&password=${password}`);
            xhr.onreadystatechange = function() {
              if (xhr.readyState === 4 && xhr.status === 200 ) {
               //邏輯處理
              }
            }
          } 
        })
      }
複製代碼

下面開始寫nodejava

  • 引入相應的模塊
    • const http = require('http');
    • const url = require('url');
    • const querystring = require('querystring'); //處理post請求參數
    • const fs =require('fs'); //讀取文件模塊
  • 存儲請求數據
    • const user = {} eg:username:'',password:'';
  • 建立一個服務器
    const server = http.createServer((req,res)=>{
        res.setHeader('Access-Control-Allow-Origin', '*'); //設置請求頭跨域
        //post請求
        let str = '';
        req.on('data', (data) => {
            str += data;
        })
        req.on('end', () => {
            const {username, password} = querystring.parse(str); //獲取請求參數
        })
        server.listen('8080',()=>{
          console.log('localhost:8080');
        })
    複製代碼

完整代碼node

const http = require('http');
    const url = require('url');
    const querystring = require('querystring');
    const fs =require('fs');
    const user = {}
    const server = http.createServer((req,res)=>{
      res.setHeader('Access-Control-Allow-Origin', '*');
      const {pathname, query} = url.parse(req.url,true);
      let str = '';
      req.on('data', (data) => {
        str += data;
      })
      req.on('end', () => {
        const {username, password} = querystring.parse(str);
        switch (pathname) {
          case '/register':
            if (!username) {
              res.writeHead(412);
              res.write('{code:412,msg:""}');
            } else if (!password) {
              res.writeHead(412);
              res.write('{code:412,msg:""}');
            } else if (user[username]) {
              res.writeHead(412);
              res.write('{code:412,msg:""}');
            } else {
              user[username] = password;
              res.write('{code:200,msg:"成功"}');
            }
            res.end();
            break;
          case '/login':
            if (!username) {
              res.writeHead(412);
              res.write('{code:412,msg:"請輸入用戶名"}');
            } else if (!password) {
              res.writeHead(412);
              res.write('{code:412,msg:"請輸入密碼"}');
            } else if (!user[username]) {
              res.writeHead(412);
              res.write('{code:412,msg:"用戶名不存在"}');
            } else if (user[username] !== password) {
              res.writeHead(412);
              res.write('{code:412,msg:"密碼錯誤"}');
            } else {
              res.write('{code:200,msg:"成功"}');
            }
            res.end();
            break;
          default:
            fs.readFile(`user/${pathname}`,(err, data)=>{
              if (err) {
                res.writeHead(404);
                res.write('Not found');
              } else {
                res.write(data);
              }
              res.end();
            })
            break;
        }
      })
    })
    server.listen('8080',()=>{
      console.log('localhost:8080');
    })
複製代碼
相關文章
相關標籤/搜索