当前位置: 移动技术网 > IT编程>脚本编程>NodeJs > 如何利用Node.js与JSON搭建简单的动态服务器

如何利用Node.js与JSON搭建简单的动态服务器

2020年08月17日  | 移动技术网IT编程  | 我要评论
一、创建html页面创建4个页面,、register.html、sign_in.html、home.html 默认主页 register.html 用于注

一、创建html页面

创建4个页面,、register.html、sign_in.html、home.html

  • 默认主页
  • register.html 用于注册账号
  • sign_in.html 用于登录账号
  • home.html 用于显示登录后的页面

主要代码片段

register.html

<form id="registerform">
 <div>
  <label for="">用户名:<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 = $('#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('注册成功')
  location.href = '/sign_in.html'
 }, () => {})
})
</script>

sign_in.html

<form id="signinform">
 <div>
  <label for="">用户名:<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服务器

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

if (!port) {
 console.log('请输入指定端口。如:\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 文件,转化为对象
 const session = json.parse(fs.readfilesync('./session.json').tostring())

 if (path === '/sign_in' && method === 'post') {
  // 读数据库
  let userarray = json.parse(fs.readfilesync('./database/users.json'))
  const array = []
  // 每次接受数据就添加进数组
  request.on('data', (chunk) => {
   array.push(chunk)
  })
  request.on('end', () => {
   // 转化字符串
   const string = buffer.concat(array).tostring()
   // 在转化为对象
   const obj = json.parse(string)
   // 找到符合的 user
   const user = userarray.find(user => user.name === obj.name && user.password === obj.password) // 成功返回符合的对象,失败返回undefined
   if (user === undefined) { // 失败
    response.statuscode = 400
    response.setheader('content-type', 'text/json; charset=utf-8')
    response.end(`{"errorcode":4001}`)
   } else { // 成功
    response.statuscode = 200
    // 设置 cookie
    const random = math.random()
    session[random] = {
     user_id: user.id
    }
    // 写入数据
    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 中读取对应的值
   const userid = session[sessionid].user_id
   // 读数据库
   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 {
   // 读取源文件内容
   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 === '/' ? '/' : 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('监听 ' + port + ' 成功!请输入下列地址访问\nhttp://localhost:' + port)

三、主要思路

register.html

使用jquery的ajax将数据发送请求 /register 给后端,成功则跳转到 sign_in.html

数据需要使用 json.stringify 转化为字符串在提交

/register

读取 users.json 的数据,创建一个空数组,将传递过来的参数 push 进去。将数组转换为字符串,在转换为对象。
获取数据库中最小的 id 值,将数据组成新的对象,添加进入 数据库 中。

sign_in.html

使用ajax将数据发送请求 /sign_in 给后端,成功则跳转 home.html

/sign_in

读取 users.json 的数据,创建一个空数组,将传递过来的参数 push 进去。将数组转换为字符串,在转换为对象。
在读取后的数据库中,查找有没有符合条件的 user,成功返回读取后的对象,失败返回 undefined。
如果成功,设置随机数,将 随机数的值 与 user的id 绑定。并添加到 session.json 中。然后 setheader,将cookie发送到浏览器。

/home

获取登入成功后 cookie 的值。读取 session 中对应的随机数。如果随机数和session对应的随机数值存在,就显示已登录,否则显示未登录

总结

到此这篇关于如何利用node.js与json搭建简单的动态服务器的文章就介绍到这了,更多相关node.js与json搭建动态服务器内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网