GET請求:
const url = 'http://localhost:3000/api/select';
// 創(chuàng)建一個Headers對象來添加自定義header
const headers = new Headers();
headers.append('token', 'xxxxx'); // 替換為實際的header名稱和值
// 使用fetch發(fā)送GET請求,并帶上headers
fetch(url, {
? method: 'GET', // 或者可以省略,因為GET是默認方法
? headers: headers, // 將headers對象作為選項的一部分
? mode: 'cors', // 如果跨域請求,需要設置mode為'cors'
? credentials: 'same-origin' // 根據需要設置,如果需要攜帶cookie等憑證
})
.then(response => {
? // 檢查響應是否成功 (狀態(tài)碼在200-299之間)
? if (!response.ok) {
? ? throw new Error('Network response was not ok');
? }
? // 解析JSON
? return response.json();
})
.then(data => {
? // 處理響應數(shù)據
? console.log(data); // 在控制臺打印數(shù)據
})
.catch(error => {
? console.error('There has been a problem with your fetch operation:', error);
});
POST請求:
const url = 'http://localhost:3000/api/create';
// 創(chuàng)建一個對象作為請求體
const data = {
? name: 'John Doe',
? email: 'johndoe@example.com',
};
// 使用fetch發(fā)送POST請求
fetch(url, {
? method: 'POST', // 指定請求方法為POST
? headers: {
? ? 'Content-Type': 'application/json', // 設置請求頭,告訴服務器發(fā)送的是JSON數(shù)據
? },
? body: JSON.stringify(data) // 將JavaScript對象轉換為JSON字符串作為請求體
})
.then(response => {
? // 檢查響應是否成功 (狀態(tài)碼在200-299之間)
? if (!response.ok) {
? ? throw new Error('Network response was not ok');
? }
? // 如果需要,可以返回解析后的JSON數(shù)據
? return response.json();
})
.then(data => {
? // 處理響應數(shù)據
? console.log(data); // 在控制臺打印返回的數(shù)據
})
.catch(error => {
? console.error('There has been a problem with your fetch operation:', error);
});