本地测试前端+Django是否存在跨域问题

本地测试前端+Django是否存在跨域问题

前端

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
            <title>
                query httprequest
            </title>
            <script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js">
            </script>
        </meta>
    </head>
    <body>
    	<button id="bid">
            123123
        </button>
        <script type="text/javascript">
            $('#bid').click(function(){
				$.ajax({
				url:'http://localhost:8000/user/',//地址
				dataType:'json',//数据类型
				type:'Post',//类型
				timeout:2000,//超时
				headers:{
				't1':'237275a110f14b038dbfc5339f255af2',
				},
				
				//请求成功
				success:function(data,status){
					//alert(data);
					//alert(status);
				},
				//失败/超时
				error:function(XMLHttpRequest,textStatus,errorThrown){
					if(textStatus==='timeout'){
						alert('請求超時');
						setTimeout(function(){
							alert('重新请求');
						},2000);
					}
					//alert(errorThrown);
				}
			})
		})
        </script>     
    </body>
</html>


Django项目的配置文件中的中间件

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
     #'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

启动Djagno后台项目

D:\drf_manage>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, session
s.
Run 'python manage.py migrate' to apply them.
April 15, 2021 - 13:34:38
Django version 3.1.7, using settings 'drf_manage.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

前端请求

后台接收请求

添加跨域中间件(可以参考 必须在common这个中间件上面)

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'middleware.corsmiddleware.CorsMiddleware',  # 解决跨域问题
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

再次查看前端请求

成功解决

撒花★,°:.☆( ̄▽ ̄)/$:.°★

posted @ 2021-04-15 13:54  Jruing  阅读(122)  评论(0编辑  收藏  举报