前端登陆调用后端api

前言

在Django服务器端写了一个API,返回JSON格式数据。前端登陆页面通过Ajax调用该API。

实例

login.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>login</title>
    </head>
    <body>
        <body>
            <div id="center">
                <form id="Form"  >
                        账号 <input type="text" id="adminName" class="adminname" name="phone"  value="" /> <br />
                        密码 <input type="password" id="psw" class="pwd" name="password" value="" /> <br />
                        <input type="button"   value="登陆" onclick="testAjax()" />
                </form> 
            </div>

            <script src="js/ajax.js"></script>
            <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    </body>
</html>

ajax.js

function testAjax() {   
    var adminName = document.getElementById('adminName').value;//获取html表单中adminName输入域对象的值,既账号
    var psw = document.getElementById('psw').value;
    var user={       
        phone:adminName, 
        password:psw,
    };
    
    $.ajax({        
        type:'POST',     
        data:JSON.stringify(user),     
        contentType :'application/json',       
        dataType:'json',   
        url :'api地址',
        success :function(result){            
            if (result.status=="true"){
                
                //输出响应的message信息
                alert(result.message)
            }else{
                alert(result.message)
            }
        },
        error: function(xmlHttpRequest, textStatus, errorThrown){
            alert("请求对象XMLHttpRequest: "+XMLHttpRequest);
            alert("错误类型textStatus: "+textStatus);                        
            alert("异常对象errorThrown: "+errorThrown); 
        }   
    });
}

结果报错了。
错误信息:
Access to XMLHttpRequest at '服务器地址' from origin 'http://127.0.0.1:8848' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

原因
这是由于ajax跨域访问引起的。所谓跨域就是,在www.aaa.com域下,访问www.bbb.com域下的资源;出于安全的考虑浏览器允许跨域写,而不允许跨域读,写就是上行(发送请求send reques),读就是下行(接受响应receive response)。

解决方法

  1. 临时解决方法: 给chrome浏览器添加参数

打开cmd命令进入chrome浏览器目录,执行以下命令

chrome.exe --disable-web-security --user-agent="Android" --user-data-dir="C:/temp-chrome-eng

mac系统

open -a Google\ Chrome --args --disable-web-security --user-data-dir="/Users/thantshweaung/Documents/Project/ionic/chrome_cache"
  1. 永久解决方法:安装django-cors-headers
pip install django-cors-headers

在settings.py中增加:

INSTALLED_APPS = (
  ...
  'corsheaders',
  ...
)
 
...
 
MIDDLEWARE  =  [  
    ... 
    'corsheaders.middleware.CorsMiddleware' ,
    'django.middleware.common.CommonMiddleware' ,
    ... 
]

CORS_ORIGIN_ALLOW_ALL = True

django-cors-headers详见:https://github.com/ottoyiu/django-cors-headers/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • http协议 Resource,URL,Request,Response,Headers http 请求的是资源R...
    Sharise_Mo佩珊阅读 3,957评论 0 4
  • 什么是跨域 跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实...
    HeroXin阅读 4,330评论 0 4
  • 什么是跨域 跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实...
    Yaoxue9阅读 5,154评论 0 6
  • 什么是跨域 跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实...
    他方l阅读 4,721评论 0 2
  • 1 上午,在家搞卫生,我妈看见我在弄那张席子,然后她用一惯的语气纠正我的做法,我立马被触碰到了开关,我把席子摔下地...
    CherryHuang阅读 1,585评论 2 5

友情链接更多精彩内容