一、同源策略

https://www.cnblogs.com/yuanchenqi/articles/7638956.html

同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。

同源策略,它是由Netscape提出的一个著名的安全策略。现在所有支持JavaScript 的浏览器都会使用这个策略。所谓同源是指,域名,协议,端口相同。
当一个浏览器的两个tab页中分别打开来 百度和谷歌的页面当浏览器的百度tab页执行一个脚本的时候会检查这个脚本是属于哪个页面的,即检查是否同源,只有和百度同源的脚本才会被执行。
如果非同源,那么在请求数据时,浏览器会在控制台中报一个异常,提示拒绝访问。
 

1、同源效果

2、非同源

注意:url:'http://127.0.0.1:8002/service/  跨域访问,浏览器拦截了!!

其实/8002/service.... 已经访问了,但是由于 浏览器的同源策略  给拦截了!!

3、code

127.0.0.1:8001:JsonpDemo1

  1. from django.contrib import admin
  2. from django.urls import path, re_path
  3. from app01 import views
  4.  
  5. urlpatterns = [
  6. path('admin/', admin.site.urls),
  7. re_path(r'index/', views.index),
  8. re_path(r'server/', views.server),
  9. ]
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <h3>jsonp1</h3>
  10. <button class="get_server">alex</button>
  11.  
  12. <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
  13.  
  14. <script type="text/javascript">
  15. $('.get_server').click(function () {
  16. $.ajax({
  17. url:'http://127.0.0.1:8002/server/',
  18. success:function (data) {
  19. console.log(data)
  20. }
  21. })
  22. })
  23. </script>
  24. </body>
  25.  
  26. </html>
  1. from django.shortcuts import render,HttpResponse
  2.  
  3. # Create your views here.
  4.  
  5. def index(request):
  6.  
  7. return render(request, 'index.html')
  8.  
  9. def server(request):
  10.  
  11. return HttpResponse("alex1")

127.0.0.1:8002:jsonDemo2

  1. from django.contrib import admin
  2. from django.urls import path,re_path
  3. from app01 import views
  4.  
  5. urlpatterns = [
  6. path('admin/', admin.site.urls),
  7. re_path(r'index/',views.index),
  8. re_path(r'server/',views.server),
  9. ]
  1. from django.shortcuts import render
  2.  
  3. # Create your views here.
  4. from django.shortcuts import render,HttpResponse
  5.  
  6. # Create your views here.
  7.  
  8. def index(request):
  9. return render(request, 'index.html')
  10.  
  11. def server(request):
  12. print("egon2222")
  13.  
  14. return HttpResponse("egon2")
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <h3>jsonp2</h3>
  10. <button class="get_server">alex</button>
  11. </body>
  12. <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
  13. <script type="text/javascript">
  14. $('.get_server').click(function () {
  15. $.ajax({
  16. url:'/server/',
  17. success:function (data) {
  18. console.log(data)
  19. }
  20. })
  21. })
  22. </script>
  23. </html>

二、jsonp

这其实就是JSONP的简单实现模式,或者说是JSONP的原型:创建一个回调函数,然后在远程服务上调用这个函数并且将JSON 数据形式作为参数传递,完成回调。

将JSON数据填充进回调函数,这就是JSONP的JSON+Padding的含义。

一般情况下,我们希望这个script标签能够动态的调用,而不是像上面因为固定在html里面所以没等页面显示就执行了,很不灵活。我们可以通过javascript动态的创建script标签,这样我们就可以灵活调用远程服务了。

1、版本1:借助script标签,实现跨域请求

jsonp是json用来跨域的一个东西。原理是通过script标签的跨域特性来绕过同源策略。

  1. 那这是,怎么回事呢? 这也是跨域呀!!
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

8001 .html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <h3>jsonp1</h3>
  10. <button class="get_server">alex</button>
  11.  
  12. <script type="text/javascript">
  13.  
  14. function egon(arg) {
  15. console.log(arg);
  16. console.log(typeof arg);
  17. var data = JSON.parse(arg);
  18. console.log(data);
  19. console.log(typeof data);
  20. }
  21. </script>
  22.  
  23. <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  24. <script src="http://127.0.0.1:8002/server/"></script>
  25.  
  26. <script>
  27. egon()
  28. </script>
  29.  
  30. </body>
  31. </html>

8002 view

  1. from django.shortcuts import render
  2.  
  3. # Create your views here.
  4. from django.shortcuts import render, HttpResponse
  5.  
  6. # Create your views here.
  7.  
  8. def index(request):
  9. return render(request, 'index.html')
  10.  
  11. import json
  12.  
  13. def server(request):
  14. print("egon2222")
  15.  
  16. info = {"name": "egon", "age": 33, "price": 200}
  17. return HttpResponse("egon('%s')" % json.dumps(info))
  18.  
  19. # return HttpResponse("egon('111')")

2、版本2:动态创建script标签

注意:

   function func(arg) {}  必须和 8005的 HttpResponse("func('%s')"%json.dumps(info))  保持一致!

BUT:

  如何将 主动权 掌握在 客户端 这边?

8002 views

  1. import json
  2.  
  3. def server(request):
  4. print("egon2222")
  5.  
  6. info = {"name": "egon", "age": 33, "price": 200}
  7. func = request.GET.get("callbacks")
  8.  
  9. return HttpResponse("%s('%s')" % (func, json.dumps(info)))
  10.  
  11. # return HttpResponse("egon('111')")

8001 html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <h3>jsonp1</h3>
  10. <button class="get_server">alex</button>
  11.  
  12. <script type="text/javascript">
  13. function egon(arg) {
  14. console.log(arg);
  15. console.log(typeof arg);
  16. var data = JSON.parse(arg);
  17. console.log(data);
  18. console.log(typeof data);
  19. }
  20. </script>
  21.  
  22. <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  23.  
  24. {## 版本2#}
  25. <script>
  26. function get_jsonp_date(url) {
  27. var jsonp_ = $('<script>');
  28. jsonp_.attr('src', url);
  29. jsonp_.attr('id', 'jsonp');
  30. $('body').append(jsonp_);
  31. $('#jsonp').remove()
  32. }
  33.  
  34. $('.get_server').click(function () {
  35. get_jsonp_date('http://127.0.0.1:8002/server/?callbacks=egon');
  36. //如何将 主动权 掌握在 客户端 这边? {"callbacks":'egon'}
  37. })
  38. </script>

3、版本3:jquery对jsonp的实现

func 不用单独定义一个函数  ?? 其实,jqeury会自动生成随机 str,不用我们管!!

code

8001 html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <h3>jsonp1</h3>
  10. <button class="get_server">alex</button>
  11.  
  12. <script type="text/javascript">
  13. function func(arg) {
  14. console.log(arg);
  15. console.log(typeof arg);
  16. var data = JSON.parse(arg);
  17. console.log(data);
  18. console.log(typeof data);
  19. }
  20. </script>
  21.  
  22. <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  23.  
  24. # 版本3
  25. <script>
  26. $('.get_server').click(function () {
  27. $.ajax({
  28. url:'http://127.0.0.1:8002/server/',
  29. type:'post',
  30. dataType:'jsonp', //伪造ajax 基于script,本质上利用script src属性
  31. jsonp:'callbacks',
  32. // jsonpCallback:'func'
  33. success:function (arg) {
  34. console.log(arg)
  35. console.log(typeof arg)
  36. var data = JSON.parse(arg)
  37. console.log(arg)
  38. console.log(typeof arg)
  39.  
  40. }
  41. })
  42. })
  43. </script>
  44.  
  45. </body>
  46. </html>

8002 同上

4、版本4:jsonp应用

code

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <h3>jsonp1</h3>
  10. <button class="get_server">alex</button>
  11.  
  12. <script type="text/javascript">
  13. function func(arg) {
  14. console.log(arg);
  15. console.log(typeof arg);
  16. var data = JSON.parse(arg);
  17. console.log(data);
  18. console.log(typeof data);
  19. }
  20. </script>
  21.  
  22. <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  23.  
  24. <script>
  25.  
  26. $(".get_server").click(function () {
  27. $.ajax({
  28. url: 'http://www.jxntv.cn/data/jmd-jxtv2.html',
  29. dataType: 'jsonp',
  30. jsonp: 'callbacks',
  31. jsonpCallback: 'list',
  32. success: function (arg) {
  33. console.log(arg.data);
  34.  
  35. var html = "";
  36. $.each(arg.data, function (i, weekday) {
  37. console.log(weekday.week); // {week: "周日", list: Array(19)}
  38. html += '<p>' + weekday.week + '</p>';
  39.  
  40. $.each(weekday.list, function (j, show) {
  41. console.log(show);
  42. html += '<p><span>' + show.time.slice(0, 2) + ':' + show.time.slice(2, 4) +
  43. '</span><a href=' + show.link + '>' + show.name + '</a></p>'
  44. })
  45. });
  46.  
  47. $('body').append(html)
  48. }
  49. })
  50. })
  51. </script>
  52.  
  53. </body>
  54. </html>

5、版本5:cors跨域请求

code

8002 server

  1. from django.shortcuts import render, HttpResponse
  2.  
  3. def index(request):
  4. return render(request, 'index.html')
  5.  
  6. import json
  7. def server(request):
  8. info = {"name": "egon", "age": 33, "price": 200}
  9. response = HttpResponse(json.dumps(info))
  10.  
  11. # 告诉浏览器你别拦截了
  12. response['Access-Control-Allow-Origin'] = "http://127.0.0.1:8001"
  13. # response['Access-Control-Allow-Origin'] = "*" # 所有的ip
  14.  
  15. return response

8001 html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <h3>jsonp1</h3>
  10. <button class="get_server">alex</button>
  11.  
  12. <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  13.  
  14. <script type="text/javascript">
  15. $('.get_server').click(function () {
  16. $('.get_server').click(function () {
  17. $.ajax({
  18. url: 'http://127.0.0.1:8002/server/',
  19. success: function (arg) {
  20. console.log(arg)
  21. console.log(typeof arg)
  22. var data = JSON.parse(arg)
  23. console.log(data)
  24. console.log(data)
  25. }
  26. })
  27. })
  28.  
  29. })
  30. </script>
  31. </body>
  32. </html>

6、补充cors - 简单请求,复杂请求

https://www.cnblogs.com/yuanchenqi/articles/7638956.html#_label7

http://www.cnblogs.com/wupeiqi/articles/5703697.html

CORS是一种允许当前域(domain)的资源(比如html/js/web service)被其他域(domain)的脚本请求访问的机制,通常由于同域安全策略(the same-origin security policy)浏览器会禁止这种跨域请求。

一、简介

CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。

整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。

因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。

二、两种请求

浏览器将CORS请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。

只要同时满足以下两大条件,就属于简单请求。

  1. 1) 请求方法是以下三种方法之一:
  2. HEAD
  3. GET
  4. POST
  5. 2HTTP的头信息不超出以下几种字段:
  6. Accept
  7. Accept-Language
  8. Content-Language
  9. Last-Event-ID
  10. Content-Type:只限于三个值application/x-www-form-urlencodedmultipart/form-datatext/plain

凡是不同时满足上面两个条件,就属于非简单请求。

浏览器对这两种请求的处理,是不一样的。

  1. * 简单请求和非简单请求的区别?
  2.  
  3. 简单请求:一次请求
  4. 非简单请求:两次请求,在发送数据之前会先发一次请求用于做“预检”,只有“预检”通过后才再发送一次请求用于数据传输。
  5. * 关于“预检”
  6.  
  7. - 请求方式:OPTIONS
  8. - “预检”其实做检查,检查如果通过则允许传输数据,检查不通过则不再发送真正想要发送的消息
  9. - 如何“预检”
  10. => 如果复杂请求是PUT等请求,则服务端需要设置允许某请求,否则“预检”不通过
  11. Access-Control-Request-Method
  12. => 如果复杂请求设置了请求头,则服务端需要设置允许某请求头,否则“预检”不通过
  13. Access-Control-Request-Headers
 

支持跨域,简单请求

服务器设置响应头:Access-Control-Allow-Origin = '域名' 或 '*'

支持跨域,复杂请求

由于复杂请求时,首先会发送“预检”请求,如果“预检”成功,则发送真实数据。

  • “预检”请求时,允许请求方式则需服务器设置响应头:Access-Control-Request-Method
  • “预检”请求时,允许请求头则需服务器设置响应头:Access-Control-Request-Headers
  1. 简单请求 复杂请求
  2. 条件:
  3.  
  4. 1、请求方式:HEADGETPOST
  5. 2、请求头信息:
  6. Accept
  7. Accept-Language
  8. Content-Language
  9. Last-Event-ID
  10. Content-Type 对应的值是以下三个中的任意一个
  11. application/x-www-form-urlencoded
  12. multipart/form-data
  13. text/plain
  14.  
  15. 注意:同时满足以上两个条件时,则是简单请求,否则为复杂请求
  16.  
  17. 如果是复杂请求:
  18. options请求进行预检,通过之后才能发送POST请求

遇到跨域,简单请求 复杂请求

写一个中间件:

cors.py:

  1. from django.utils.deprecation import MiddlewareMixin
  2.  
  3. class CORSMiddleware(MiddlewareMixin):
  4. def process_response(self,request,response):
  5. # 允许你的域名来访问
  6. response['Access-Control-Allow-Origin'] = "*"
  7.  
  8. if request.method == 'OPTIONS':
  9. # 允许你携带 Content-Type 请求头 不能写*
  10. response['Access-Control-Allow-Headers'] = 'Content-Type'
  11. # 允许你发送 DELETE PUT请求
  12. response['Access-Control-Allow-Methods'] = 'DELETE,PUT'
  13.  
  14. return response

4 伪ajax:jsonp、cors 跨域请求的更多相关文章

  1. ajax jsonp的跨域请求

    1.页面ajax的请求 $.ajax({ async: false, url: 'http://localhost:8080/downloadVideos',//跨域的dns/document!sea ...

  2. PHP AJAX JSONP实现跨域请求使用实例

    在之前我写过“php返回json数据简单实例”,“php返回json数据中文显示的问题”和“在PHP语言中使用JSON和将json还原成数组”.有兴趣的童鞋可以看看 今天我写的是PHP AJAX JS ...

  3. Spring Boot Web应用开发 CORS 跨域请求支持:

    Spring Boot Web应用开发 CORS 跨域请求支持: 一.Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等CORS与JSONP相比 1. JSONP只能实现 ...

  4. js中ajax如何解决跨域请求

    js中ajax如何解决跨域请求,在讲这个问题之前先解释几个名词 1.跨域请求 所有的浏览器都是同源策略,这个策略能保证页面脚本资源和cookie安全 ,浏览器隔离了来自不同源的请求,防上跨域不安全的操 ...

  5. 使用jsonp进行跨域请求

    使用jsonp进行跨域请求 在实际的业务中很多时候需要用到跨域请求,然而jsonp为我们提供了一种非常方便的跨域请求的方式,具体实现代码如下: $.ajax({ type:"get" ...

  6. CORS跨域请求总结

    CORS跨域请求分为简单请求和复杂请求. 1. 简单请求: 满足一下两个条件的请求. (1) 请求方法是以下三种方法之一: HEAD GET POST (2)HTTP的头信息不超出以下几种字段: Ac ...

  7. CORS跨域请求规则以及在Spring中的实现

    CORS: 通常情况下浏览器禁止AJAX从外部获取资源,因此就衍生了CORS这一标准体系,来实现跨域请求. CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origi ...

  8. 关于使用Jsonp做跨域请求

    今天在使用Jsonp做跨域请求的练习时碰上这样一个问题 代码如下 <!DOCTYPE html> <html> <head> <meta charset=&q ...

  9. Nginx反向代理、CORS、JSONP等跨域请求解决方法总结

    由于 Javascript 同源策略的存在使得一个源中加载来自其它源中资源的行为受到了限制.即会出现跨域请求禁止. 通俗一点说就是如果存在协议.域名.端口或者子域名不同服务端,或一者为IP地址,一者为 ...

随机推荐

  1. uml各类图

    原文:http://www.cnblogs.com/way-peng/archive/2012/06/11/2544932.html 一.UML是什么?UML有什么用? 二.UML的历史 三.UML的 ...

  2. 如何快速的给你的项目添加icon图标

    如何快速的给你的项目添加icon图标 下载软件 如何制作图片 将制作的图标拖到项目当中 设置启动页 注意: 如果手动添加了启动页的话,记得将Launch Screen中的东西清除掉

  3. ARC下block使用情况

    ARC与MRC的block有着一些区别,笔记整理ARC的block,仅仅是自己参考的笔记,详情请参考 http://www.cnbluebox.com/?p=255 在开始之前,请新建一个Model类 ...

  4. UIView的无损截图

    UIView的无损截图 说明 1. 烂大街的代码 2. 写成category后,方便直接从drawRect中获取绘制出来的图片 3. 可以直接绘制图片供按钮设置背景图片用 4. 无损截图(包括alph ...

  5. [翻译] ZCSHoldProgress

    ZCSHoldProgress 以下是使用效果: https://github.com/zshannon/ZCSHoldProgress "Your users be pressin' lo ...

  6. 【2】python3字符串的比较(辨析is与==的区别)

    PYTHON3基本数据类型(二.字符串) Python3字符串 ①字符串比较 1.比较字符串是否相同: ==:使用==来比较两个字符串内的value值是否相同 is:比较两个字符串的id值. 2.字符 ...

  7. UI(二)之正式过程

    2018-12-04 09:48:25 1.SetWindowsHookEx ·钩子实际上是一个处理消息的程序段,通过系统调用,把它挂入系统.每当特定的消息发出,在没有到达目的窗口前,钩子程序就先捕获 ...

  8. codeforces 1007B Pave the Parallelepiped

    codeforces 1007B Pave the Parallelepiped 题意 题解 代码 #include<bits/stdc++.h> using namespace std; ...

  9. 团队作业—预则立&&他山之石(改)

    首先特别感谢刘乾学长腾出他宝贵的时间接受我的采访,为我们提出宝贵的建议,深表感谢. 1.他山之石,可以攻玉.借鉴前人的经验可以使我们减少很多走弯路的地方,这也是本次采访的目的,参考历届学长的经验,让我 ...

  10. 鼠标有但是U盘读取不出来怎么办

    我今天就遇到了这个问题,搞了半天最后下了一个驱动人生,查看里面的回答才解决 就是把里面通用串行总控制器设置为隐藏文件可读之后选择把灰色的都删除就好了.具体可以在驱动人生里搜U盘不识别,之后就4,5步即 ...