为了测试的目的,经常须要准备一个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命令验证服务的有效性:ios
GET操做ajax
$curl http://localhost:8080/todo/1
$curl http://localhost:8080/todos
复制代码
DELETE操做express
$ curl -X "DELETE" http://localhost:8080/todo/1
复制代码
PUT操做npm
$curl -X PUT -H "Content-Type: application/json" -d '{"id" : "2","subject":"s2222"}' http://localhost:8080/todo/1
复制代码
POST操做json
$curl -X POST -H "Content-Type: application/json" -d '{"id" : "4","subject":"s4"}' http://localhost:8080/todo
复制代码
建立一个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.
复制代码
相比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>
复制代码