// 使用 fetch 进行跨域请求的示例代码
// 1. 简单 GET 请求 (CORS 预检请求)
fetch('https://api.example.com/data', {
method: 'GET',
mode: 'cors', // 指定跨域请求模式为 CORS
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // 解析 JSON 响应
})
.then(data => console.log(data)) // 处理返回的数据
.catch(error => console.error('There was a problem with the fetch operation:', error));
// 2. POST 请求 (包含自定义头部,会触发 CORS 预检请求)
fetch('https://api.example.com/post', {
method: 'POST',
mode: 'cors', // 指定跨域请求模式为 CORS
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token' // 自定义头部
},
body: JSON.stringify({
key1: 'value1',
key2: 'value2'
})
})
.then(response => response.json()) // 解析 JSON 响应
.then(data => console.log(data)) // 处理返回的数据
.catch(error => console.error('There was a problem with the fetch operation:', error));
// 3. 使用 no-cors 模式(仅限于同源请求或对不支持 CORS 的资源进行请求)
// 注意:no-cors 模式下,如果请求的资源不支持 CORS,则无法访问响应数据
fetch('https://api.example.com/data', {
method: 'GET',
mode: 'no-cors' // 不建议使用,除非你明确知道你要做什么
})
.then(response => response.blob()) // 解析为 Blob 对象
.then(blob => console.log(blob))
.catch(error => console.error('There was a problem with the fetch operation:', error));
GET、POST、HEAD),或者请求中包含自定义头部时,浏览器会在实际请求之前发送一个 OPTIONS 请求,以确认服务器是否允许该跨域请求。上一篇:js ...是什么意思
下一篇:nodejs fetch
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站