跨源请求,也称为CORS(Cross-Origin Resource Sharing)请求,是Web开发中常见的一种需求,允许一个网页的JavaScript代码向与该网页不同源的服务器发出HTTP请求。以下是使用JavaScript中的fetch函数进行跨源请求的一个基本示例:
这里做测试的是前端http://127.0.0.1:5500/fetchcors.html
后端:http://xuejx.xyz/fetchcors.php
他们是在不同的域下,进行跨域请求
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<title>测试fetch的跨域请求</title>
</head>
<body>
<script>
//跨域请求后端URL
const url='http://xuejs.xyz/fetchcors.php';
//fetch的第2个参数init对象配置
const options={
method:'GET',//请求模式get
headers:{
'Content-Type':'application/json'//设置请求标头数据为json格式
},
};
fetch(url,options)
.then((response)=>{
if(!response.ok)
{
throw new Error('network response was not ok');
}
//response.type是请求返回的数据特征,这里结果为:cors表示跨域
console.log(response.type);
//获取后端返回数据转化为json,json()是response的方法,会自动转化为json
return response.json();
})
.then(data=>{
console.log(data);//显示返回数据
})
.catch(error=>{
console.log('fetch操作发生一个错误:',error);
});
</script>
</body>
</html>
//后端fetchcors.php
// 检查是否是OPTIONS请求,如果是,则发送CORS预检请求的响应
if ($_SERVER[‘REQUEST_METHOD’] == ‘OPTIONS’) {
header(‘Access-Control-Allow-Origin: *’); // 允许跨域访问的域名,*代表允许所有域名
header(‘Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS’); // 允许的HTTP方法这几种
header(‘Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With’); // 允许的头信息有这三种
header(‘Access-Control-Max-Age: 1728000’); // 设置预检请求的有效时间
exit;
}
<?php
//允许前端请求的域名
$allow_orgin='http://127.0.0.1:5500';
//OPTIONS 请求方式是 HTTP 协议中的一种,主要用于从响应头中获取服务器支持的HTTP请求方式
if($_SERVER['REQUEST_METHOD']=='OPTIONS')
{
header('Access-Control-Allow-Origin:'.$allow_orgin);//设置前端跨域的域名
header('Access-Control-Allow-Methods:GET');//请求方式为GET
header('Access-Control-Allow-Headers:Content-Type');//请求的数据格式
header('Access-Control-Max-Age:300000');//请求的预检时间为5分钟
exit;//设置完后退出
}
//现在设置本页面的数据格式
header("Content-Type:application/json");
//本页面允许的跨域请求前端域名
header('Access-Control-Allow-Origin:'.$allow_orgin);
//返回给前端的数据
$data=[
'id'=>1,
'name'=>'James doe',
'email'=>'James@163.com'
];
echo json_encode($data);
?>