为了测试的目的,常常需要准备一个todo应用的后台json服务,可以通过HTTP方式,提供todo项目的增加删除修改和查询。
这样的服务器,使用了nodejs作为服务器端,并且使用了两个node模块,可以使用npm安装它们:
npm install express body-parser
复制代码
body-parser是一个中间件,可以解析请求内容并把解析结果放到req.body属性内。最常见的做法就是解析json内容。
代码如下(文件名为:jsonserver.js):
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 jsonserver.js
复制代码
Curl命令验证
可以通过curl命令验证服务的有效性:
-
GET操作
$curl http://localhost:8080/todo/1 $curl http://localhost:8080/todos 复制代码
-
DELETE操作
$ curl -X "DELETE" http://localhost:8080/todo/1 复制代码
-
PUT操作
$curl -X PUT -H "Content-Type: application/json" -d '{"id" : "2","subject":"s2222"}' http://localhost:8080/todo/1 复制代码
-
POST操作
$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>
复制代码