目录
Ajax请求限制
Ajax 只能向自己的服务器发送请求。比如现在有一个A网站、有一个B网站,A网站中的 HTML 文件只能向A网站服务器中发送 Ajax 请求,B网站中的 HTML 文件只能向 B 网站中发送 Ajax 请求,但是 A 网站是不能向 B 网站发送 Ajax请求的,同理,B 网站也不能向 A 网站发送 Ajax请求。
什么是同源
如果两个页面拥有相同的协议、域名和端口,那么这两个页面就属于同一个源,其中只要有一个不相同,就是不同源。
http://www.example.com/dir/page.html
http://www.example.com/dir2/other.html:同源
http://example.com/dir/other.html:不同源(域名不同)
http://v2.www.example.com/dir/other.html:不同源(域名不同)
http://www.example.com:81/dir/other.html:不同源(端口不同)
https://www.example.com/dir/page.html:不同源(协议不同)
同源政策的目的
同源政策是为了保证用户信息的安全,防止恶意的网站窃取数据。最初的同源政策是指 A 网站在客户端设置的 Cookie,B网站是不能访问的。
随着互联网的发展,同源政策也越来越严格,在不同源的情况下,其中有一项规定就是无法向非同源地址发送Ajax 请求,如果请求,浏览器就会报错。
使用 JSONP 解决同源限制问题
jsonp 是 json with padding 的缩写,它不属于 Ajax 请求,但它可以模拟 Ajax 请求。
<script src="www.example.com"></script>
<script src=“https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
const data = 'fn({name: "张三", age: "20"})';
res.send(data);
- 在客户端全局作用域下定义函数 fn
function fn (data) { }
- 在 fn 函数内部对服务器端返回的数据进行处理
function fn (data) { console.log(data); }
JSONP 代码优化
<script src="http://localhost:3001/better?callback=fn"></script>
然后在服务器进行拼接,再返回给客户端
2.将 script 请求的发送变成动态请求。
btn.onclick = function () {
// 创建script标签
var script = document.createElement('script');
// 设置src属性
script.src = 'http://localhost:3001/better?callback=fn2';
// 将script标签追加到页面中
document.body.appendChild(script);
// 为script标签添加onload事件
script.onload = function () {
// 将body中的script标签删除掉
document.body.removeChild(script);
}
}
3.封装 jsonp 函数,方便请求发送。
function jsonp (options) {
// 动态创建script标签
var script = document.createElement('script');
// 拼接字符串的变量
var params = '';
for (var attr in options.data) {
params += '&' + attr + '=' + options.data[attr];
}
// myJsonp0124741
var fnName = 'myJsonp' + Math.random().toString().replace('.', '');
// 将它变成全局函数
window[fnName] = options.success;
// 为script标签添加src属性
script.src = options.url + '?callback=' + fnName + params;
// 将script标签追加到页面中
document.body.appendChild(script);
// 为script标签添加onload事件
script.onload = function () {
document.body.removeChild(script);
}
}
//调用函数
btn.onclick = function () {
jsonp({
// 请求地址
url: 'http://localhost:3001/better',
data: {
name: 'lisi',
age: 30
},
success: function (data) {
console.log(123)
console.log(data)
}
})
}
app.get('/better', (req, res) => {
res.jsonp({name: 'lisi', age: 20});
});
在nodejs的express框架中为我们提供res.jsonp()方法,方法传递一个json对象,内部会自动拼接方法名称与对象参数,并返回给客户端
自动拼接:fnName + '('+ data +')'
案例:获取腾讯天气
接口文档
-
请求地址
-
请求方式
- get 支持jsonp
-
参数
参数名 必填 类型 说明 source 是 string pc(电脑)、xw(手机) weather_type 是 string forecast_1h 未来48时
forecast_24h 未来7天
多个参数用 | 隔开province 是 string 省份 city 是 string 城市 -
返回值
{ "data": { //逐时天气(48小时) "forecast_1h": { "0": { "degree": "19",//温度 "update_time": "20200328220000",//时间 "weather": "小雨",//天气名称 "weather_code": "07",//天气码 "weather_short": "小雨",//天气简要名称 "wind_direction": "东风",//风向 "wind_power": "3"//风力级别 } } }, "message": "OK", "status": 200 }
实例:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>使用jsonp获取腾讯天气信息</title> <link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css"> <style type="text/css"> .container { padding-top: 60px; } </style> </head> <body> <div class="container"> <table class="table table-striped table-hover" align="center" id="Box"></table> </div> <script src="/js/jsonp.js"></script> <script src="/js/template-web.js"></script> <script type="text/html" id="tpl"> <tr> <th>时间</th> <th>温度</th> <th>天气</th> <th>风向</th> <th>风力</th> </tr> {{each info}} <tr> <td>{{dateFormat($value.update_time)}}</td> <td>{{$value.degree}}</td> <td>{{$value.weather}}</td> <td>{{$value.wind_direction}}</td> <td>{{$value.wind_power}}</td> </tr> {{/each}} </script> <script> // 获取table标签 var Box = document.getElementById('Box'); function dateFormat(date){ var year = date.substr(0,4); var month = date.substr(4,2); var day = date.substr(6,2); var hour = date.substr(8,2); var minute = date.substr(10,2); var seconds = date.substr(12,2); return year + '年' + month + '月' + day + '日' + hour + '时' + minute + '分' + seconds + '秒'; } //向模板中开放外部变量 template.defaults.imports.dateFormat = dateFormat; // 用自定义封装的jsonp函数向服务器端获取天气信息 jsonp({ url:'https://wis.qq.com/weather/common', data:{ source:'pc', weather_type:'forecast_1h', province:'广西壮族自治区', city:'南宁' }, success:function(data){ var html = template('tpl',{info:data.data.forecast_1h}); Box.innerHTML = html; } }); </script> </body> </html>
CORS 跨域资源共享
CORS:全称为 Cross-origin resource sharing,即跨域资源共享,它允许浏览器向跨域服务器发送 Ajax 请求,克服了 Ajax 只能同源使用的限制。
发送地址:
origin: http://localhost:3000
服务器端响应:
Access-Control-Allow-Origin: 'http://localhost:3000'
Access-Control-Allow-Origin: '*'
Node 服务器端设置响应头示例代码:
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');//设置所有地址请求通过
res.header('Access-Control-Allow-Methods', 'GET, POST');//允许的方法
next();
})
访问非同源数据 服务器端解决方案
同源政策是浏览器给予Ajax技术的限制,服务器端是不存在同源政策限制。
Node 服务器端示例代码
// 向其他服务器端请求数据的模块
const request = require('request');
app.get('/server', (req, res) => {
//向其他服务器发送请求,然后返回给客户端
request('http://localhost:3001/cross', (err, response, body) => {
res.send(body);
})
});
withCredentials属性
在使用Ajax技术发送跨域请求时,默认情况下不会在请求中携带cookie信息。
withCredentials:客户端指定在涉及到跨域请求时,是否携带cookie信息,默认值为false
Access-Control-Allow-Credentials:true 允许客户端发送请求时携带cookie
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。