tenx() 方法属于fetchAPI的一部分 它返回一个Promise实例对象 用于获取后台返回的数据 可调用后面的then方法
// fetch的基本用法
fetch('http://localhost:2021/fetch').then((data) => {
return data.text();
// 这里的then里面的data不能直接输出 需要return data.text()
// data.text() 是一个 Promise 对象 可以调用下一个 then
// tenx() 方法属于fetchAPI的一部分 它返回一个Promise实例对象 用于获取后台返回的数据
}).then((ret) => {
console.log(ret);
})
1.fetch常用配置选项
method: GET/POST/PUT/DELETE 默认为get
body:HTTP的请求参数
headers:HTTP的请求头 默认为{}
传统形式的URL传参 GET请求
app.get('/fetch1', (req, res) => {
res.send('通过URL传参' + "___" + req.query.name + "___" + req.query.id)
})
fetch('http://localhost:2021/fetch1?name=wanghao&&id=170508020139', {
method: 'GET',
}).then((data) => {
return data.text();
})
.then((ret) => {
console.log(ret);
})
festful形式的URL传参 GET请求
app.get('/fetch11/:name/:id', (req, res) => {
res.send('restful形式的URL传参' + "___" + req.params.name + "___" + req.params.id)
})
fetch('http://localhost:2021/fetch11/wanghao/170508020139', {
method: 'GET',
})
.then((data) => {
return data.text();
}).then((ret) => {
console.log(ret);
});
POST请求
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/fetchPost', (req, res) => {
res.send('post传参' + "___" + req.body.name + "___" + req.body.id)
})
// POST 请求传参
// 传统方法
fetch('http://localhost:2021/fetchPost', {
method: 'post',
body: 'name=wanghao&id=170508020139',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then((data) => {
return data.text();
})
.then((ret) => {
console.log(ret);
});
// json
fetch('http://localhost:2021/fetchPost', {
method: 'post',
body: JSON.stringify({
name: 'wanghao',
id: 1407777777777
}),
headers: {
'Content-Type': 'application/json'
}
}).then((data) => {
return data.text();
})
.then((ret) => {
console.log(ret);
});
fetch响应结果
1 text() 将返回的结果处理成字符串类型
2 json() 将结果和json.parse(responseText)一样
// text() 将返回的结果处理成字符串类型
fetch('http://localhost:2021/fetch11/wanghao/170508020139', {
method: 'get',
})
.then((data) => {
return data.text();
}).then((ret) => {
console.log(ret);
});
// json() 将结果和json.parse(responseText)一样
app.get('/json', (req, res) => {
res.json({
name: 'json',
id: 147
})
})
fetch('http://localhost:2021/json').then(data => {
return data.json();
}).then(ret => {
console.log(ret);
})