GET请求:
const url = 'http://localhost:3000/api/select';
// 创建一个Headers对象来添加自定义header
const headers = new Headers();
headers.append('token', 'xxxxx'); // 替换为实际的header名称和值
// 使用fetch发送GET请求,并带上headers
fetch(url, {
method: 'GET', // 或者可以省略,因为GET是默认方法
headers: headers, // 将headers对象作为选项的一部分
mode: 'cors', // 如果跨域请求,需要设置mode为'cors'
credentials: 'same-origin' // 根据需要设置,如果需要携带cookie等凭证
})
.then(response => {
// 检查响应是否成功 (状态码在200-299之间)
if (!response.ok) {
throw new Error('Network response was not ok');
}
// 解析JSON
return response.json();
})
.then(data => {
// 处理响应数据
console.log(data); // 在控制台打印数据
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
POST请求:
const url = 'http://localhost:3000/api/create';
// 创建一个对象作为请求体
const data = {
name: 'John Doe',
email: 'johndoe@example.com',
};
// 使用fetch发送POST请求
fetch(url, {
method: 'POST', // 指定请求方法为POST
headers: {
'Content-Type': 'application/json', // 设置请求头,告诉服务器发送的是JSON数据
},
body: JSON.stringify(data) // 将JavaScript对象转换为JSON字符串作为请求体
})
.then(response => {
// 检查响应是否成功 (状态码在200-299之间)
if (!response.ok) {
throw new Error('Network response was not ok');
}
// 如果需要,可以返回解析后的JSON数据
return response.json();
})
.then(data => {
// 处理响应数据
console.log(data); // 在控制台打印返回的数据
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});