接口调用Fetch
- GET请求
app.get('/books', (req, res) => {
res.send('传统的url传递参数' + req.query.id)
})
app.get('/books/:id', (req, res) => {
res.send('Restful的url传递参数' + req.params.id)
})
- POST请求
fetch('http://localhost:3000/books', {
method: 'post',
body: 'uname=list&pwd=123',
headers: {
'Content-Type': "application/x-www-form-urlencoded"
}
})
.then(function(data) {
return data.text()
}).then(function(data) {
console.log(data)
})
app.post('/books', (req, res) => {
res.send('POST的url传递参数' + req.body.uname + req.body.pwd)
// body-parser提供body
// 支持json数据格式
})
-
PUT请求
-
fetch响应结果
returndata.text()
:将返回体处理为字符串类型
returndata.json()
:返回结果和JSON.parse(responseText)一样
// fetch响应结果的数据格式
fetch('http://localhost:3000/json')
.then(function(data) {
return data.json()
// return data.text()
}).then(function(data) {
// console.log(data.uname)
// console.log(typeof data)object
console.log(data)
或者
// var obj = JSON.parse(data)
// obj.name,obj,age,obj.gender
})
app.get('/json', (req, res) => {
res.json({
uname: 'jack',
uage: 12,
gender: 'female'
})
})