Ajax跨域
1. 同源策略
同源:协议、域名、端口号必须完全相同
违背同源策略就是跨域
2. JSONP的实现原理
1)JSONP是什么
JSONP(JSON with Padding),是一个非官方的跨域解决方案,纯粹凭借程序员的聪明才智开发出来,只支持get 请求。
2)JSONP怎么工作的?
在网页有一些标签天生具有跨域能力,比如:img link iframe script 。
JSONP就是利用script标签的跨域能力来发送请求的。
3)实践
// 1.引入express
const express = require('express');
// 2.创建应用对象
const app = express();
// 3.创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
app.all('/check-username',(request,response)=>{
const data ={
exist: 1,
msg:'用户名已经存在'
};
//将数据转化为字符串
let str = JSON.stringify(data);
//返回结果
response.end(`handle(${str})`);
});
// 4.监听窗口启动服务
app.listen(8000,()=>{
console.log("服务意见启动,8000端口监听中。。。")
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jsonp案例</title>
</head>
<body>
用户名 :<input type="text" id="username" />
<p></p>
<script>
//获取input 元素
const input = document.querySelector('input');
const p = document.querySelector('p');
function handle(data){
input.style.border = "solid 1px #f00";
}
//绑定事件
input.onblur = function(){
//获取用户的输入值
let username = this.value;
//向服务器端发送请求 检测用户名是否存在
//1.创建script 标签
const script = document.createElement('script');
//2.设置标签的src属性
script.src = 'http://127.0.0.1:8000/check-username';
//3.将script标签插入到文档中
document.body.appendChild(script);
}
</script>
</body>
</html>
3. jQuery发送jsonp请求
// 1.引入express
const express = require('express');
// 2.创建应用对象
const app = express();
// 3.创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
app.all('/jquery-jsonp-server',(request,response)=>{
const data ={
name: 121,
city:['beijing','shanghai','shenzhen']
};
//将数据转化为字符串
let str = JSON.stringify(data);
//接收callback 参数
let cb = request.query.callback;
//返回结果
response.end(`${cb}(${str})`);
});
// 4.监听窗口启动服务
app.listen(8000,()=>{
console.log("服务意见启动,8000端口监听中。。。")
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jq-jsonp</title>
<style>
#result{
width: 300px;
height: 100px;
border: solid 1px #089;
}
</style>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button>点击发送jsonp请求</button>
<div id="result">
</div>
<script>
$('button').eq(0).click(function() {
$.getJSON('http://127.0.0.1:8000//jquery-jsonp-server?callback=?',function(){
$('#result').html(`
名称:${data.name},<br>
校区:${data.city}
`)
})
});
</script>
</body>
</html>
4. CORS
1.CORS是什么?
CORS (Kross-Origin Resource Sharing〉,跨域资源共享。CORS是官方的跨域解决方案,它的特点是不需要在客户端做任何特殊的操作,完全在服务器中进行处理,支持get和post 请求。跨域资源共享标准新增了一组HTTP首部字段,允许服务器声明哪些源站通过浏览器有权限访问哪些资源
2.CORS怎么工作的?
CORS是通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应以后就会对响应放行。
// 1.引入express
const express = require('express');
// 2.创建应用对象
const app = express();
// 3.创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
app.all('/cors-server',(request,response)=>{
//设置响应头
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Headers","*");
response.setHeader("Access-Control-Allow-Method","*");
response.send('hello cors');
});
// 4.监听窗口启动服务
app.listen(8000,()=>{
console.log("服务意见启动,8000端口监听中。。。")
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CORS</title>
<style>
#result{
width: 300px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<button>发送请求</button>
<div id="result">
</div>
<script type="text/javascript">
const btn = document.querySelector('button');
btn.onclick = function(){
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化设置
xhr.open('get','http://127.0.0.1:8000/cors-server');
//3.发送
xhr.send();
//4.绑定事件
xhr.onreadystatechange = function(){
if(xhr.readyState ===4){
if(xhr.status>=200 && xhr.status<300){
console.log(xhr.response);
}
}
}
}
</script>
</body>
</html>