• cors跨域


    cors跨域

    什么是跨域

    跨域(跨源)是指浏览器从一个源的网页去请求另一个源,源指的是域名、端口、协议
    以下都属于跨域问题
    域名: 
        主域名不同: http://www.baidu.com/index.html –> http://www.sina.com/test.js 
        子域名不同: http://www.666.baidu.com/index.html –> http://www.555.baidu.com/test.js 
        域名和域名ip: http://www.baidu.com/index.html –>http://180.149.132.47/test.js 
    端口: 
        http://www.baidu.com:8080/index.html–> http://www.baidu.com:8081/test.js 
    协议: 
        http://www.baidu.com:8080/index.html–> https://www.baidu.com:8080/test.js 
     

    为什么要考虑跨域问题

    因为Ajax不能跨域, 一旦客户端和服务的不在一台服务器, 则需要考虑跨域访问的问题
     

    同源策略

    同源策略是浏览器的一项最为基本同时也是必须遵守的安全策略。
    同源策略的存在,限制了“源”自A的脚本只能操作“同源”页面的DOM,“跨源”操作来源于B的页面将会被拒绝。
    所谓的“同源”,必须要求相应的URI的域名、端口、协议均是相同的。
     

    解决跨域问题

    方式一: 使用JSONP(一种非Ajax技术,需要前后端同时支持)

    方式二: 让服务器支持跨域(推荐)

    Django支持跨域
    安装django-cors-headers
        pip install django-cors-headers
    配置settings.py文件
        INSTALLED_APPS = [
            'corsheaders'
         ]
        MIDDLEWARE_CLASSES = (
            'corsheaders.middleware.CorsMiddleware',
            'django.middleware.common.CommonMiddleware', 
        )
        # 跨域增加忽略
        CORS_ALLOW_CREDENTIALS = True
        CORS_ORIGIN_ALLOW_ALL = True
        CORS_ORIGIN_WHITELIST = ('*')
    
    
        # 跨域允许的请求方式(可选)
        CORS_ALLOW_METHODS = (
            'DELETE',
            'GET',
            'OPTIONS',
            'PATCH',
            'POST',
            'PUT',
        )
    
    
        # 跨域允许的头部参数(可选)
        CORS_ALLOW_HEADERS = (
            'XMLHttpRequest',
            'X_FILENAME',
            'accept-encoding',
            'authorization',
            'content-type',
            'dnt',
            'origin',
            'user-agent',
            'x-csrftoken',
            'x-requested-with',
            'Pragma',
        )
     
    Flask支持跨域
    安装flask_cors
        pip install flask-cors
        
    使用flask_corsCORS
        from flask_cors import CORS
        CORS(app, supports_credentials=True)
        
     
  • 相关阅读:
    leetcode 【 Merge Two Sorted Lists 】 python 实现
    leetcode 【 Remove Duplicates from Sorted List II 】 python 实现
    leetcode 【 Remove Duplicates from Sorted List 】 python 实现
    leetcode 【 Remove Nth Node From End of List 】 python 实现
    leetcode 【 Linked List Swap Nodes in Pairs 】 python 实现
    i++操作非原子的验证代码
    黑马MySQL数据库学习day03 级联 多表查询 连接和子查询 表约束
    mysql 原理 ~ sql查询语句
    tidb 架构 ~Tidb学习系列(3)
    mysql 查询优化 ~ 善用profie利器
  • 原文地址:https://www.cnblogs.com/gugubeng/p/9722569.html
Copyright © 2020-2023  润新知