欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何利用Node.js與JSON搭建簡(jiǎn)單的動(dòng)態(tài)服務(wù)器

 更新時(shí)間:2020年06月16日 08:43:51   作者:努力了嗎梁同學(xué)  
這篇文章主要給大家介紹了關(guān)于如何利用Node.js與JSON搭建簡(jiǎn)單的動(dòng)態(tài)服務(wù)器的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Node.js具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

一、創(chuàng)建html頁(yè)面

創(chuàng)建4個(gè)頁(yè)面,index.html、register.html、sign_in.html、home.html

  • index.html 默認(rèn)主頁(yè)
  • register.html 用于注冊(cè)賬號(hào)
  • sign_in.html 用于登錄賬號(hào)
  • home.html 用于顯示登錄后的頁(yè)面

主要代碼片段

register.html

<form id="registerForm">
 <div>
  <label for="">用戶(hù)名:<input type="text" name="name" id=""></label>
 </div>
 <div>
  <label for="">密碼:<input type="password" name="password" id=""></label>
 </div>
 <div>
  <button type="submit">注冊(cè)</button>
 </div>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
let $form = $('#registerForm')
$form.on('submit', (e) => {
 e.preventDefault()
 const name = $form.find("input[name=name]").val()
 const password = $form.find('input[name=password').val()
 console.log(name, password)
 // pass AJAX post data
 $.ajax({
  method: 'post',
  url: '/register',
  contentType: 'text/json; charset=UTF-8',
  data: JSON.stringify({
   name, // name: name 
   password // password: password
  })
 }).then(() => {
  alert('注冊(cè)成功')
  location.href = '/sign_in.html'
 }, () => {})
})
</script>

sign_in.html

<form id="signInForm">
 <div>
  <label for="">用戶(hù)名:<input type="text" name="name" id=""></label>
 </div>
 <div>
  <label for="">密碼:<input type="password" name="password" id=""></label>
 </div>
 <div>
  <button type="submit">登錄</button>
 </div>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
 let $form = $('#signInForm')
 $form.on('submit', (e) => {
  e.preventDefault()
  // get name password
  const name = $form.find("input[name=name]").val()
  const password = $form.find('input[name=password').val()
  // pass AJAX post data
  $.ajax({
   method: 'POST',
   url: '/sign_in',
   contentType: 'text/json; charset=UTF-8',
   data: JSON.stringify({
    name,
    password
   })
  }).then(() => {
   alert('登錄成功')
   location.href = '/home.html'
  }, () => {})
 })
</script>

home.html

<p>
 {{loginStatus}}
</p>
<p>
 你好,{{user.name}}
</p>
<p>
 <a href="sign_in.html">登錄</a>
</p>

二、Node服務(wù)器

var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if (!port) {
 console.log('請(qǐng)輸入指定端口。如:\nnode server.js 8888')
 process.exit(1)
}

var server = http.createServer(function (request, response) {
 var parsedUrl = url.parse(request.url, true)
 var pathWithQuery = request.url
 var queryString = ''
 if (pathWithQuery.indexOf('?') >= 0) {
  queryString = pathWithQuery.substring(pathWithQuery.indexOf('?'))
 }
 var path = parsedUrl.pathname
 var query = parsedUrl.query
 var method = request.method

 /******** main start ************/
 // 讀取 session 文件,轉(zhuǎn)化為對(duì)象
 const session = JSON.parse(fs.readFileSync('./session.json').toString())

 if (path === '/sign_in' && method === 'POST') {
  // 讀數(shù)據(jù)庫(kù)
  let userArray = JSON.parse(fs.readFileSync('./database/users.json'))
  const array = []
  // 每次接受數(shù)據(jù)就添加進(jìn)數(shù)組
  request.on('data', (chunk) => {
   array.push(chunk)
  })
  request.on('end', () => {
   // 轉(zhuǎn)化字符串
   const string = Buffer.concat(array).toString()
   // 在轉(zhuǎn)化為對(duì)象
   const obj = JSON.parse(string)
   // 找到符合的 user
   const user = userArray.find(user => user.name === obj.name && user.password === obj.password) // 成功返回符合的對(duì)象,失敗返回undefined
   if (user === undefined) { // 失敗
    response.statusCode = 400
    response.setHeader('content-Type', 'text/JSON; charset=UTF-8')
    response.end(`{"errorCode":4001}`)
   } else { // 成功
    response.statusCode = 200
    // 設(shè)置 Cookie
    const random = Math.random()
    session[random] = {
     user_id: user.id
    }
    // 寫(xiě)入數(shù)據(jù)
    fs.writeFileSync('./session.json', JSON.stringify(session))
    response.setHeader("Set-Cookie", `'session_id=${random}; HttpOnly'`)
    response.end()
   }
  })
 } else if (path === '/home.html') {
  // 獲取 Cookie
  const cookie = request.headers['cookie']
  let sessionId
  try { // 讀取 Cookie 中的 id 值
   sessionId = cookie.split(';').filter(s => s.indexOf('session_id=') >= 0)[0].split('=')[1]
  } catch (error) {}
  if (sessionId && session[sessionId]) {
   // 從 session 中讀取對(duì)應(yīng)的值
   const userId = session[sessionId].user_id
   // 讀數(shù)據(jù)庫(kù)
   let userArray = JSON.parse(fs.readFileSync('./database/users.json'))
   // 找到符合的 user
   let user = userArray.find(user => user.id === userId)
   const homeHtml = fs.readFileSync('./public/home.html').toString()
   let string
   if (user) {
    string = homeHtml.replace('{{loginStatus}}', '已登錄').replace('{{user.name}}', user.name)
    response.write(string)
   }
  } else {
   // 讀取源文件內(nèi)容
   const homeHtml = fs.readFileSync('./public/home.html').toString()
   // 替換文字
   const string = homeHtml.replace('{{loginStatus}}', '未登錄').replace('{{user.name}}', '')
   response.write(string)
  }
  response.end()
 } else if (path === '/register' && method === 'POST') {
  response.setHeader('Content-Type', 'text/html; charset=UTF-8')
  // read database
  let userArray = JSON.parse(fs.readFileSync('./database/users.json')) // read database
  const array = []
  request.on('data', (chunk) => {
   array.push(chunk)
  })
  request.on('end', () => {
   // convert string
   const string = Buffer.concat(array).toString()
   // convert obj
   const obj = JSON.parse(string)
   // last user id
   const lastUser = userArray[userArray.length - 1]
   // new user
   const newUser = {
    id: lastUser ? lastUser.id + 1 : 1,
    name: obj.name,
    password: obj.password
   }
   userArray.push(newUser)
   // write data
   fs.writeFileSync('./database/users.json', JSON.stringify(userArray))
  })
  response.end()
 } else {
  response.statusCode = 200
  let content
  // setting index
  const filePath = path === '/' ? '/index.html' : path
  // judge type
  const index = filePath.lastIndexOf('.')
  const suffix = filePath.substring(index)
  const fileType = {
   '.html': 'text/html',
   '.css': 'text/css',
   '.js': 'text/javascript'
  }
  response.setHeader('Content-Type', `${fileType[suffix] || "text/html"};charset=utf-8`)
  try {
   content = fs.readFileSync(`./public${filePath}`)
  } catch (error) {
   content = '文件路徑不存在'
   response.statusCode = 404
  }
  response.write(content)
  response.end()
 }

 /******** main end ************/
})

server.listen(port)
console.log('監(jiān)聽(tīng) ' + port + ' 成功!請(qǐng)輸入下列地址訪(fǎng)問(wèn)\nhttp://localhost:' + port)

三、主要思路

register.html

使用jQuery的ajax將數(shù)據(jù)發(fā)送請(qǐng)求 /register 給后端,成功則跳轉(zhuǎn)到 sign_in.html

數(shù)據(jù)需要使用 JSON.stringify 轉(zhuǎn)化為字符串在提交

/register

讀取 users.json 的數(shù)據(jù),創(chuàng)建一個(gè)空數(shù)組,將傳遞過(guò)來(lái)的參數(shù) push 進(jìn)去。將數(shù)組轉(zhuǎn)換為字符串,在轉(zhuǎn)換為對(duì)象。
獲取數(shù)據(jù)庫(kù)中最小的 id 值,將數(shù)據(jù)組成新的對(duì)象,添加進(jìn)入 數(shù)據(jù)庫(kù) 中。

sign_in.html

使用ajax將數(shù)據(jù)發(fā)送請(qǐng)求 /sign_in 給后端,成功則跳轉(zhuǎn) home.html

/sign_in

讀取 users.json 的數(shù)據(jù),創(chuàng)建一個(gè)空數(shù)組,將傳遞過(guò)來(lái)的參數(shù) push 進(jìn)去。將數(shù)組轉(zhuǎn)換為字符串,在轉(zhuǎn)換為對(duì)象。
在讀取后的數(shù)據(jù)庫(kù)中,查找有沒(méi)有符合條件的 user,成功返回讀取后的對(duì)象,失敗返回 undefined。
如果成功,設(shè)置隨機(jī)數(shù),將 隨機(jī)數(shù)的值 與 user的id 綁定。并添加到 session.json 中。然后 setHeader,將cookie發(fā)送到瀏覽器。

/home

獲取登入成功后 cookie 的值。讀取 session 中對(duì)應(yīng)的隨機(jī)數(shù)。如果隨機(jī)數(shù)和session對(duì)應(yīng)的隨機(jī)數(shù)值存在,就顯示已登錄,否則顯示未登錄

總結(jié)

到此這篇關(guān)于如何利用Node.js與JSON搭建簡(jiǎn)單的動(dòng)態(tài)服務(wù)器的文章就介紹到這了,更多相關(guān)Node.js與JSON搭建動(dòng)態(tài)服務(wù)器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 一文學(xué)會(huì)搭建HTTP服務(wù)器調(diào)用DLL庫(kù)

    一文學(xué)會(huì)搭建HTTP服務(wù)器調(diào)用DLL庫(kù)

    這篇文章主要為大家介紹了一文學(xué)會(huì)搭建HTTP服務(wù)器調(diào)用DLL庫(kù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • 淺析 NodeJs 的幾種文件路徑

    淺析 NodeJs 的幾種文件路徑

    本篇文章主要介紹了淺析 NodeJs 的幾種文件路徑,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-06-06
  • 基于Node.js搭建hexo博客過(guò)程詳解

    基于Node.js搭建hexo博客過(guò)程詳解

    這篇文章主要介紹了基于Node.js搭建hexo博客過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,
    2019-06-06
  • node微信小程序登錄實(shí)現(xiàn)登錄的項(xiàng)目實(shí)踐

    node微信小程序登錄實(shí)現(xiàn)登錄的項(xiàng)目實(shí)踐

    登陸流程是指小程序用戶(hù)進(jìn)行授權(quán)登陸,即獲取用戶(hù)的微信賬號(hào)等信息本文就來(lái)介紹一下node微信小程序登錄實(shí)現(xiàn)登錄,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-09-09
  • 詳解Node.Js如何處理post數(shù)據(jù)

    詳解Node.Js如何處理post數(shù)據(jù)

    這篇文章給大家介紹了如何利用Node.Js處理post數(shù)據(jù),文中通過(guò)實(shí)例和圖文介紹的很詳細(xì),有需要的小伙伴們可以參考借鑒,下面來(lái)一起看看吧。
    2016-09-09
  • 淺談Node.js 中間件模式

    淺談Node.js 中間件模式

    中間件在 Node.js 中被廣泛使用,它泛指一種特定的設(shè)計(jì)模式、一系列的處理單元、過(guò)濾器和處理程序,以函數(shù)的形式存在,這篇文章主要介紹了淺談Node.js 中間件模式,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • Nodejs實(shí)現(xiàn)短信驗(yàn)證碼功能

    Nodejs實(shí)現(xiàn)短信驗(yàn)證碼功能

    使用Nodejs的開(kāi)發(fā)者愈來(lái)越多,基于Nodejs的后臺(tái)開(kāi)發(fā)也多了起來(lái),像短信驗(yàn)證碼、短信群發(fā)、國(guó)際短信這些需求,完全可以采用第三方接口來(lái)實(shí)現(xiàn),云片就提供了這樣的接口
    2017-02-02
  • Node如何實(shí)現(xiàn)在瀏覽器預(yù)覽項(xiàng)目的所有圖片詳解

    Node如何實(shí)現(xiàn)在瀏覽器預(yù)覽項(xiàng)目的所有圖片詳解

    最近項(xiàng)目遇到了個(gè)需求,需要將存放圖片進(jìn)行預(yù)覽,所以這篇文章主要給大家介紹了關(guān)于Node如何實(shí)現(xiàn)在瀏覽器預(yù)覽項(xiàng)目的所有圖片的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-01-01
  • 阿里大于短信驗(yàn)證碼node koa2的實(shí)現(xiàn)代碼(最新)

    阿里大于短信驗(yàn)證碼node koa2的實(shí)現(xiàn)代碼(最新)

    本文給大家分享一個(gè)最新版阿里大于短信驗(yàn)證碼node koa2的實(shí)現(xiàn)代碼及注意事項(xiàng),需要的朋友參考下吧
    2017-09-09
  • Nest.js中使用HTTP五種數(shù)據(jù)傳輸方式小結(jié)

    Nest.js中使用HTTP五種數(shù)據(jù)傳輸方式小結(jié)

    本文主要介紹了Nest.js中使用HTTP五種數(shù)據(jù)傳輸方式小結(jié),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05

最新評(píng)論