一、beegoget請求參數
在使用fetchget請求參數前,需要了解beego框架中的get請求參數。
beego框架中的get請求參數通過c.Ctx.Input.Query(key)方法獲取,key為參數名,返回值為參數值。
func (c *MainController) Get() {
key := c.Ctx.Input.Query("key")
fmt.Printf("get request, key=%s\n", key)
c.Ctx.WriteString("get request success")
}
上述的代碼演示了如何在beego框架中獲取get請求參數。
二、fetchget請求
fetchget請求是通過fetch API發起的get請求。
fetchget請求的格式如下:
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
其中url為請求的地址,data為請求參數,可以是一個JSON對象。headers為請求頭,Content-Type為請求內容的類型,這裡設置為application/json。fetchget請求如果成功,則會返回一個JSON對象,通過response.json()方法解析返回的數據。
三、fetch模擬put請求
在fetch中,還可以使用put方法模擬put請求,代碼如下:
fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
與fetchget請求類似,需要注意的是請求方法需要設置為PUT。
四、fetch請求如何中斷
在fetch請求過程中,有時需要中斷請求,可以使用AbortController來實現。代碼如下:
const controller = new AbortController();
const signal = controller.signal;
fetch(url, {
method: 'GET',
signal: signal
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
controller.abort();
AbortController創建一個AbortSignal對象,可以傳遞給fetch中的signal參數來中斷請求。在上述代碼中,調用controller.abort()方法即可中斷fetch請求。
五、get請求的參數怎麼隱藏
在get請求中,將參數放在url中不安全,可以使用POST方法在請求體中發送參數,隱藏參數。代碼如下:
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
在上述代碼中,fetch請求的方法設置為POST,請求體中發送參數,通過JSON.stringify()方法將參數轉換為JSON格式。
六、fetch請求
除了fetchget請求外,還有fetch的其他請求參數。
fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrer: 'no-referrer',
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
fetch的其他請求參數包括mode、cache、credentials、redirect、referrer等,可以根據具體需求設置參數。
七、fetch請求API接口
在使用fetch請求API接口時,需要提前了解API文檔,根據API文檔中的要求設置請求參數和路徑。
fetch('https://api.example.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
以上代碼演示了如何使用fetch請求API接口。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/252061.html