get请求
- fetch默认就是get请求
- get请求携带参数,url+?key=value&key=value
- 语法:
async function get1(url) {
let res = await fetch(url)
.then(response => response.json())
.catch(err => err.json())
console.log(res);
}
async function get2(url) {
let res = await fetch(url + "?q=新疆")
.then(r => r.json())
.catch(err => err.json())
console.log(res);
}
post请求
- 在请求体
body中,传递参数
- 需要修改数据格式为 key=value&key=value&
- 还需要设置header的传输格式
- 语法:
const Params = (obj) => {
let str = ""
for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
str += `${key}=${obj[key]}&`
}
}
return str
}
async function post(url) {
let user = {
name: "张三",
age: 26,
sex: "男",
address: "江苏"
}
let res = await fetch(url, {
method: "post",
body: Params(user),
headers: {
"content-type": "application/x-www-form-urlencoded"
}
}).then(response => response.json())
console.log(res);
}
delete 请求
async function del(url) {
let res = await fetch(url + "/" + 13, {
method: "delete"
}).then(r => r.json())
console.log(res);
}
put 全部修改
- PUT全部修改,相当于覆盖
- 在请求体
body中,传递参数
- 需要修改数据格式为 key=value&key=value&
- 还需要设置header的传输格式
- 语法:
const Params = (obj) => {
let str = ""
for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
str += `${key}=${obj[key]}&`
}
}
return str
}
async function put(url) {
let user = {
name: "李四",
address: "北京"
}
let res = await fetch(url + "/" + 14, {
method: "PUT",
headers: {
"content-type": "application/x-www-form-urlencoded"
},
body: Params(user)
}).then(r => r.json())
console.log(res);
}
patch 部分修改
- 在请求体
body中,传递参数
- 需要修改数据格式为 key=value&key=value&
- 还需要设置header的传输格式
- 语法:
const Params = (obj) => {
let str = ""
for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
str += `${key}=${obj[key]}&`
}
}
return str
}
async function patch(url){
let user = {
name: "喻言",
age: 50
}
let res = await fetch(url + "/" + 15, {
method: "PATCH",
headers: {
"content-type": "application/x-www-form-urlencoded"
},
body: Params(user)
}).then(r => r.json())
console.log(res);
}