準備 JSON 服務器並訪問它

爲了測試的目的,經常須要準備一個todo應用的後臺json服務,能夠經過HTTP方式,提供todo項目的增長刪除修改和查詢。javascript

這樣的服務器,使用了nodejs做爲服務器端,而且使用了兩個node模塊,可使用npm安裝它們:html

npm install express body-parser 
複製代碼

body-parser是一箇中間件,能夠解析請求內容並把解析結果放到req.body屬性內。最多見的作法就是解析json內容。前端

代碼以下(文件名爲:jsonserver.js):java

var express = require('express');
var app = express();
var path = require('path')
var bodyParser = require('body-parser')
app.use(bodyParser.json())
var todos = []
var public = path.join(__dirname, '/')
app.use('/',express.static(public))
function indexById(id){
  for (var i = 0; i < todos.length; i++) {
    if (+todos[i].id == id)
      return i
  }
}
function rs(){
  todos = [
         {"id" : "1","subject":"s1"},
         {"id" : "2","subject":"s2"},
         {"id" : "3","subject":"s3"},
      ]
}
rs()
app.put('/todo/:id', function (req, res) {
  var userkey = indexbyId(parseInt(req.params.id))
  todos[userkey] = req.body
  res.end( JSON.stringify(todos));
  rs()
})
app.delete('/todo/:id', function (req, res) {
  console.log('here is DELETE')
  var userkey = indexById(parseInt(req.params.id))
  todos.splice(userkey,1)
  res.end( JSON.stringify(todos));
  rs()
})
app.get('/todo/:id', function (req, res) {
  var userkey = indexById(parseInt(req.params.id))
  res.end( JSON.stringify(todos[userkey]));
})
app.get('/todos', function (req, res) {
  res.end( JSON.stringify(todos));
})
app.post('/todo', function (req, res) {
  todos.push(req.body)
  res.end(JSON.stringify(todos))
  rs()
})
var server = app.listen(3000, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("listening at http://%s:%s", host, port)
})
複製代碼

可使用命令執行:node

node jsonserver.js
複製代碼

Curl命令驗證

能夠經過curl命令驗證服務的有效性:ios

  1. GET操做ajax

    $curl http://localhost:8080/todo/1
      $curl http://localhost:8080/todos
    複製代碼
  2. DELETE操做express

    $ curl -X "DELETE" http://localhost:8080/todo/1
    複製代碼
  3. PUT操做npm

    $curl -X PUT  -H "Content-Type: application/json" -d '{"id" : "2","subject":"s2222"}' http://localhost:8080/todo/1
    複製代碼
  4. POST操做json

    $curl -X POST  -H "Content-Type: application/json" -d '{"id" : "4","subject":"s4"}' http://localhost:8080/todo
    複製代碼

前端HTML驗證

建立一個index.html文件,並放置到和jsonserver.js代碼同一目錄,代碼以下:

<a href='/todos'>todos</a>
<a href='/todo/1'>todo/1</a>
<button onclick='remove()'>remove 1</button>
<button onclick='create()'>create</button>
<script>
  function remove(){
    fetch (
      '/todo/1',
      {
        method: 'DELETE',
      }
    )
    .then( res => console.log(res.json()))
    .catch( err => cosole.error(err))
  }
  function create(){
    fetch (
      '/todo',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({id: "4", subject: "s4"})
      }
    )
    .then( res => console.log(res.json()))
    .catch( err => cosole.error(err))
  }
</script>
複製代碼

能夠提供建立,刪除,列表的測試,其中部分結果在console內顯示。

提及來,JS訪問HTTP的庫真的是很多,這裏 提到的庫都有9種。其中的fetch api使用起來很是的簡潔趁手,但是它不支持IE。若是你須要支持IE的話,使用Axios更好。這就是爲何Vuejs官方推薦Axios的緣由吧:

The Fetch API is a powerful native API for these types of requests. You may have heard that one of the benefits of the Fetch API is that you don’t need to load an external resource in order to use it, which is true! Except… that it’s not fully supported yet, so you will still need to use a polyfill. There are also some gotchas when working with this API, which is why many prefer to use axios for now. This may very well change in the future though.
複製代碼

axios訪問方法

相比fetch,使用axios必須依賴於外部文件。爲了方便,咱們直接使用unpkg網站提供的庫文件。

axios的語法和fetch的大同小異,看着也是比較簡潔美觀的。如下代碼,把create和remove函數的內部實現換掉,其餘不變。

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<a href='/todos'>todos</a>
<a href='/todo/1'>todo/1</a>
<button onclick='remove()'>remove 1</button>
<button onclick='create()'>create</button>
<script>
  function remove(){
    axios ({
      	url:'/todo/1',
        method: 'DELETE',
    })
    .then( res => console.log(res.json()))
    .catch( err => cosole.error(err))
  }
  function create(){
    axios ({
        method: 'POST',
        url:'/todo',
        headers: {
          'Content-Type': 'application/json'
        },
        data: JSON.stringify({id: "4", subject: "s4"})
    })
    .then( res => console.log(res.json()))
    .catch( err => cosole.error(err))
  }
</script>
複製代碼
相關文章
相關標籤/搜索