JSONP
jsonp菜鸟教程
非官方的跨域解决方案,只支持get请求,借助script标签。
script标签本身就带有跨域特性。
例子:
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
原理
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>原理演示</title><style>#result{width:300px;height: 100px;border:solid 1px #78a;}</style></head><body><div id="result"></div><!-- <script src="./js/app.js"></script> --><script>//处理数据function handle(data){//获取result元素const result = document.getElementById("result");result.innerHTML = data.name;}</script><!-- <script src="http://127.0.0.1:5500/code/%E8%B7%A8%E5%9F%9F/2-JSONp/js/app.js"></script> --><script src="http://127.0.0.1:8000/jsonp-server"></script></body></html>
server.js
//jsonp服务app.all('/jsonp-server',(resquest,response)=>{// response.send('console.log("hello jsonp server")')//必须要js语句const data={name:"跨域ttt"};//将数据转换为字符串let str = JSON.stringify(data);//返回结果response.end(`handle(${str})`);//返回函数调用 并把参数放在里面//函数要在html里面提前声明好});
返回结果中 返回函数调用 并把参数放在里面 并且在调用的界面中 函数要提前声明
原生jsonp实践
//html<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>JSON案例</title></head><body>用户名:<input type="text" id="username"><p></p><script >//获取input元素const input = document.querySelector('input');const p = document.querySelector('p');//声明handle函数function handle(data){input.style.border = 'solid 1px #f00'//修改p标签的提示文本p.innerHTML = data.msg;}//绑定事件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>//server.js//用户名检测app.all('/check-username',(resquest,response)=>{// response.send('console.log("hello jsonp server")')//必须要js语句const data={exist:1,msg:"用户名已经存在"};//将数据转换为字符串let str = JSON.stringify(data);//返回结果response.end(`handle(${str})`);//返回函数调用 并把参数放在里面//函数要在html里面提前声明好});
jquery发送jsonp请求
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><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.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(data){// console.log(data)$('#result').html(`名称:${data.name}<br>位置:${data.city}`)});});</script></body></html>server//jq jsonpapp.all('/jquery-jsonp-server',(request,response)=>{const data={name:'jq jsonp server',city:['school','home']};//将数据转换为字符串let str = JSON.stringify(data);//接受callback参数let cb = request.query.callback;//返回结果response.end(`${cb}(${str})`);//返回函数调用 并把参数放在里面//函数要在html里面提前声明好});
CORS
cors | mdn
官方的跨域解决方案,不需要在客户端做任何特殊操作,完全在服务器中进行处理,默认支持get 和 post 请求
如何工作?
通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应后就会对该响应放行、
如果直接使用
<body><button>发送请求</button><div id="result"></div><script>const btn = document.querySelector('button');btn.onclick = function(){//1.创建对象const x = new XMLHttpRequest();//2.初始化设置x.open("GET","http://127.0.0.1:8000/cors-server");//3.发送x.send();//4.绑定事件x.onreadystatechange = function(){if(x.readyState === 4){if(x.status >= 200 ){console.log(x.response);}}}}</script>app.all('/cors-server',(request,response)=>{response.send("hello cors");})

要解决这个问题 就是在server.js 的app.all 中 设置一个响应头 其实也就是之前一直有的东西
response.setHeader(“Access-Control-Allow-Origin”,”*”);
就我目前所学而言 cors 会方便很多
更多的直接看上面那个mdn的链接 讲的非常好 非常的详细
