Django 解决同源跨域问题

Django 解决同源跨域问题

由于浏览器具有同源策略的限制:在发送Ajax请求时,如果当前浏览器的URL是a.com,而页面中向b.com发送ajax请求,请求可以正常方法,但数据回到浏览器时,浏览器就会阻止。在b.com中设置一个响应头就可以解决问题。

1 site a

1.1 urls 配置

from django.urls import path,re_path
from app01 import views

urlpatterns = [
    #    path('admin/', admin.site.urls),
    re_path('^index/$',views.IndexView.as_view()),
    re_path('^hello/$',views.HelloView.as_view()),
]

1.2 app01.views配置

from django.shortcuts import render, HttpResponse
from django.views import View


# Create your views here.

class IndexView(View):
    def get(self, request, *args, **kwargs):
        return render(request=request, template_name='index.html')


class HelloView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse('hello, it is a.com.')

1.3 index.html配置

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>a.com</h1>
<input type="button" value="b.com" onclick="localSite()">
<pre></pre>
<input type="button" value="b.com" onclick="remoteSite()">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
    function localSite() {
        $.ajax({
            url:"http://127.0.0.1:8001/hello/",
            type:"get",
            success: function (result) {
                console.log(result);
            },
            error: function () {
                console.log('Send Request Failed!');
            }
        })
    }
    function remoteSite() {
        $.ajax({
            url: "http://127.0.0.1:8002/hello/",
            type: "get",
            success: function (result) {
                console.log(result);
            },
            error: function () {
                console.log('Send Request Failed...')
            }
        })
    }
</script>
</body>
</html>

2 site b

2.1 urls 配置

from django.urls import path,re_path
from app01 import views

urlpatterns = [
    #    path('admin/', admin.site.urls),
    re_path(r'hello/$',views.helloView),
]

2.2 app01.views配置

from django.shortcuts import render,HttpResponse

# Create your views here.

def helloView(request):
    if request.method == 'GET':
        result = HttpResponse('it is b.com')
        # 以下两种方式都可以,让浏览器放行
        # result.headers['Access-Control-Allow-Origin'] = "*"
        # result['Access-Control-Allow-Origin'] = "*"
        return result
posted @ 2023-08-21 12:06  f_carey  阅读(19)  评论(0编辑  收藏  举报