為了測試的目的,常常需要準備一個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>
複製程式碼