Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js fetch 跨域

作者:整整ー世♂陰霾そ   发布日期:2025-12-13   浏览:91

// 使用 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));

解释说明:

  • mode: 'cors':这是默认模式,表示这是一个跨域请求。浏览器会自动处理 CORS(跨域资源共享)相关的预检请求。
  • mode: 'no-cors':这种模式只能用于同源请求或对不支持 CORS 的资源进行请求。它不会发送 CORS 相关的头信息,并且如果请求的资源不支持 CORS,则无法访问响应数据。
  • 预检请求(Preflight Request):当请求方法不是简单请求(如 GETPOSTHEAD),或者请求中包含自定义头部时,浏览器会在实际请求之前发送一个 OPTIONS 请求,以确认服务器是否允许该跨域请求。

上一篇:js ...是什么意思

下一篇:nodejs fetch

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站