当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 用Node编写RESTful API接口的示例代码

用Node编写RESTful API接口的示例代码

2018年08月05日  | 移动技术网IT编程  | 我要评论

前言

本文介绍了如何用node开发web程序,并通过一个todo list练习来介绍如何创建符合restful风格的api接口。

创建http服务器

用node创建http服务器是非常方便的。

创建http服务器要调用http.createserver()函数,它只有一个参数,是个回调函数,服务器每次收到http请求后都会调用这个回调函数。这个回调会收到两个参数,请求和响应对象,通常简写为req和res:

var http = require('http')
var server = http.createserver(function(req, res){
  res.end('hello world')
})
server.listen(3000, '127.0.0.1')

运行上面的代码,在浏览器中访问http://localhost:3000。然后你应该能看到一个包含“hello world.”的普通文本页面。

服务器每收到一条http请求,都会用新的req和res对象触发回调函数。

在触发回调函数之前,node会解析请求的http头,并将它们作为req对象的一部分提供给请求回调。但node不会在回调函数被触发之前开始对请求体的解析。这种做法跟某些服务端框架不同,比如php就是在程序逻辑运行前就把请求头和请求体都解析出来了。

node不会自动往客户端写任何响应。在调用完请求回调函数之后,就要由你负责用res.end()方法结束响应了(见下图)。这样在结束响应之前,你可以在请求的生命期内运行任何你想运行的异步逻辑。如果你没能结束响应,请求会挂起,直到客户端超时,或者它会一直处于打开状态。

搭建http服务器仅仅是个开始。接下来我们来看看如何设定响应状态码和响应头中的字段,如何正确处理异常。

设置响应头

可以用res.setheader(field, value)来设置相应的响应头,下面是代码:

var http = require('http')
var server = http.createserver(function(req, res){
 var body = '<h1>hello node</h1>'
 res.setheader('content-length', body.length)
 res.setheader('content-type', 'text/html')
 res.end(body)
})
server.listen(3000)

设置状态码

我们经常需要返回默认状态码200之外的http状态码。比较常见的情况是当所请求的资源不存在时返回一个404 not found状态码。

这可以通过设定res.statuscode属性来实现。在程序响应期间可以随时给这个属性赋值,但必须在第一次调用res.write()或res.end()之前。

var http = require('http')
var server = http.createserver(function(req, res) {
 var body = '<p>页面丢失了</p>'
 res.setheader('content-type', 'text/html;charset=utf-8')
 res.statuscode = 404
 res.end(body)
})
server.listen(3000, '127.0.0.1')

node的策略是提供小而强的网络api,不同于rails或django之类的框架。像会话这种高级概念以及http cookies这样的基础组件都没有包括在node的内核之中。那些都要由第三方模块提供。

构建 restful web 服务

roy fielding博士在2000年提出了表征状态转移 (rest)。它是一种基于 http 协议的网络应用的接口风格。

依照规定,比如get、post、put和delete,分别与资源的获取、创建、更新和删除相对应。

http 协议定义了以下8种标准的方法:

  1. get:请求获取指定资源。
  2. head:请求指定资源的响应头。
  3. post:向指定资源提交数据。
  4. put:请求服务器存储一个资源。
  5. delete:请求服务器删除指定资源。
  6. trace:回显服务器收到的请求,主要用于测试或诊断。
  7. connect:http/1.1 协议中预留给能够将连接改为管道方式的代理服务器。
  8. options:返回服务器支持的http请求方法。

创建标准的rest服务需要实现四个http谓词。每个谓词会覆盖一个操作:

  1. get:获取
  2. post:新增
  3. put:更新
  4. delete:删除

post和get请求

接下来,通过一个todo list练习来编写restful风格的get和post接口。

需求分析

项目采用前后端分离,交互数据格式约定为json,前端添加的数据提交到服务器后,由服务器存入服务器内存中。前端界面如下:

首先,我们先编写前端部分。

前端部分

前端采用vue.js作为框架,ajax请求采用axios库。代码如下:

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>title</title>

 <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>

<div id="app">
 <h1>todo list</h1>
 <ul>
  <li v-for="(item, index) in items" :key="index">{{ item }}</li>
 </ul>

 <input type="text" v-model="item">
 <button @click="postapi">button</button>
</div>

<script>
 new vue({
  el: '#app',
  data: {
   items: [],
   item: ''
  },
  created () {
   axios.get('http://localhost:3000/')
    .then(response => {
     this.items = response.data
    })
    .catch(function (error) {
     console.log(error)
    })
  },
  methods: {
   postapi () {
    axios.post('http://localhost:3000/', {
     item: this.item
    })
     .then(response => {
      this.items = response.data
     })
     .catch(function (error) {
      console.log(error)
     })
   }
  }
 })
</script>
</body>
</html>

后端部分

var http = require('http')

var items = []

http.createserver(function(req, res) {
 // 设置cors跨域
 res.setheader('access-control-allow-origin', '*')
 res.setheader('access-control-allow-headers', 'content-type')
 res.setheader('content-type', 'application/json')

 switch (req.method) {
  // 设置了cors跨域
  // post请求时,浏览器会先发一次options请求,如果请求通过,则继续发送正式的post请求
  case 'options':
   res.statuscode = 200
   res.end()
   break

  case 'get':
   let data = json.stringify(items)
   res.write(data)
   res.end()
   break

  case 'post':
   let item = ''
   req.on('data', function (chunk) {
    item += chunk
   })
   req.on('end', function () {
    // 存入
    item = json.parse(item)
    items.push(item.item)
    // 返回到客户端
    let data = json.stringify(items)
    res.write(data)
    res.end()
   })
   break
 }
}).listen(3000)

console.log('http server is start...')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网