GVKun编程网logo

Python | Flask 解决跨域问题(flask跨域怎么解决)

12

在这里,我们将给大家分享关于Python|Flask解决跨域问题的知识,让您更了解flask跨域怎么解决的本质,同时也会涉及到如何更有效地AJAX跨域问题解决方法(2)——JSONP解决跨域、angu

在这里,我们将给大家分享关于Python | Flask 解决跨域问题的知识,让您更了解flask跨域怎么解决的本质,同时也会涉及到如何更有效地AJAX跨域问题解决方法(2)——JSONP解决跨域、angular解决跨域问题、Flask + Nginx + React + Webpack 配置解决跨域问题、Flask-Cors:Python web应用程序中解决跨域问题的内容。

本文目录一览:

Python | Flask 解决跨域问题(flask跨域怎么解决)

Python | Flask 解决跨域问题(flask跨域怎么解决)

系列文章目录


Table of Contents

  • 系列文章目录
  • 前言
  • 使用步骤
    • 1. 引入库
    • 2. 配置
      • 1. 使用 CORS函数 配置全局路由
      • 2. 使用 @cross_origin 来配置单行路由
    • 配置参数说明
  • 总结
  • 参考

前言

我靠,又跨域了

使用步骤

1. 引入库

pip install flask-cors

2. 配置

flask-cors 有两种用法,一种为全局使用,一种对指定的路由使用

1. 使用 CORS函数 配置全局路由

from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app, supports_credentials=True)

其中 CORS 提供了一些参数帮助我们定制一下操作。

常用的我们可以配置 originsmethodsallow_headerssupports_credentials

所有的配置项如下:


:param resources:
    The series of regular expression and (optionally) associated CORS
    options to be applied to the given resource path.

    If the argument is a dictionary, it''s keys must be regular expressions,
    and the values must be a dictionary of kwargs, identical to the kwargs
    of this function.

    If the argument is a list, it is expected to be a list of regular
    expressions, for which the app-wide configured options are applied.

    If the argument is a string, it is expected to be a regular expression
    for which the app-wide configured options are applied.

    Default : Match all and apply app-level configuration

:type resources: dict, iterable or string

:param origins:
    The origin, or list of origins to allow requests from.
    The origin(s) may be regular expressions, case-sensitive strings,
    or else an asterisk

    Default : ''*''
:type origins: list, string or regex

:param methods:
    The method or list of methods which the allowed origins are allowed to
    access for non-simple requests.

    Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]
:type methods: list or string

:param expose_headers:
    The header or list which are safe to expose to the API of a CORS API
    specification.

    Default : None
:type expose_headers: list or string

:param allow_headers:
    The header or list of header field names which can be used when this
    resource is accessed by allowed origins. The header(s) may be regular
    expressions, case-sensitive strings, or else an asterisk.

    Default : ''*'', allow all headers
:type allow_headers: list, string or regex

:param supports_credentials:
    Allows users to make authenticated requests. If true, injects the
    `Access-Control-Allow-Credentials` header in responses. This allows
    cookies and credentials to be submitted across domains.

    :note: This option cannot be used in conjuction with a ''*'' origin

    Default : False
:type supports_credentials: bool

:param max_age:
    The maximum time for which this CORS request maybe cached. This value
    is set as the `Access-Control-Max-Age` header.

    Default : None
:type max_age: timedelta, integer, string or None

:param send_wildcard: If True, and the origins parameter is `*`, a wildcard
    `Access-Control-Allow-Origin` header is sent, rather than the
    request''s `Origin` header.

    Default : False
:type send_wildcard: bool

:param vary_header:
    If True, the header Vary: Origin will be returned as per the W3
    implementation guidelines.

    Setting this header when the `Access-Control-Allow-Origin` is
    dynamically generated (e.g. when there is more than one allowed
    origin, and an Origin than ''*'' is returned) informs CDNs and other
    caches that the CORS headers are dynamic, and cannot be cached.

    If False, the Vary header will never be injected or altered.

    Default : True
:type vary_header: bool

2. 使用 @cross_origin 来配置单行路由

from flask import Flask, request
from flask_cors import cross_origin

app = Flask(__name__)


@app.route(''/'')
@cross_origin(supports_credentials=True)
def hello():
    name = request.args.get("name", "World")
    return f''Hello, {name}!''

其中 cross_originCORS 提供一些基本相同的参数。

常用的我们可以配置 originsmethodsallow_headerssupports_credentials

所有的配置项如下:

:param origins:
    The origin, or list of origins to allow requests from.
    The origin(s) may be regular expressions, case-sensitive strings,
    or else an asterisk

    Default : ''*''
:type origins: list, string or regex

:param methods:
    The method or list of methods which the allowed origins are allowed to
    access for non-simple requests.

    Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]
:type methods: list or string

:param expose_headers:
    The header or list which are safe to expose to the API of a CORS API
    specification.

    Default : None
:type expose_headers: list or string

:param allow_headers:
    The header or list of header field names which can be used when this
    resource is accessed by allowed origins. The header(s) may be regular
    expressions, case-sensitive strings, or else an asterisk.

    Default : ''*'', allow all headers
:type allow_headers: list, string or regex

:param supports_credentials:
    Allows users to make authenticated requests. If true, injects the
    `Access-Control-Allow-Credentials` header in responses. This allows
    cookies and credentials to be submitted across domains.

    :note: This option cannot be used in conjuction with a ''*'' origin

    Default : False
:type supports_credentials: bool

:param max_age:
    The maximum time for which this CORS request maybe cached. This value
    is set as the `Access-Control-Max-Age` header.

    Default : None
:type max_age: timedelta, integer, string or None

:param send_wildcard: If True, and the origins parameter is `*`, a wildcard
    `Access-Control-Allow-Origin` header is sent, rather than the
    request''s `Origin` header.

    Default : False
:type send_wildcard: bool

:param vary_header:
    If True, the header Vary: Origin will be returned as per the W3
    implementation guidelines.

    Setting this header when the `Access-Control-Allow-Origin` is
    dynamically generated (e.g. when there is more than one allowed
    origin, and an Origin than ''*'' is returned) informs CDNs and other
    caches that the CORS headers are dynamic, and cannot be cached.

    If False, the Vary header will never be injected or altered.

    Default : True
:type vary_header: bool

:param automatic_options:
    Only applies to the `cross_origin` decorator. If True, Flask-CORS will
    override Flask''s default OPTIONS handling to return CORS headers for
    OPTIONS requests.

    Default : True
:type automatic_options: bool

配置参数说明

参数 类型 Head 默认 说明
resources 字典、迭代器或字符串 全部 配置允许跨域的路由接口
origins 列表、字符串或正则表达式 Access-Control-Allow-Origin * 配置允许跨域访问的源
methods 列表、字符串 Access-Control-Allow-Methods [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE] 配置跨域支持的请求方式
expose_headers 列表、字符串 Access-Control-Expose-Headers None 自定义请求响应的 Head 信息
allow_headers 列表、字符串或正则表达式 Access-Control-Request-Headers * 配置允许跨域的请求头
supports_credentials 布尔值 Access-Control-Allow-Credentials False 是否允许请求发送 cookie
max_age timedelta、整数、字符串 Access-Control-Max-Age None 预检请求的有效时长

总结

在 flask 的跨域配置中,我们可以使用 flask-cors 来进行配置,其中 CORS 函数 用来做全局的配置,@cross_origin 来实现特定路由的配置

参考

  • https://flask-cors.readthedocs.io/en/latest/

AJAX跨域问题解决方法(2)——JSONP解决跨域

AJAX跨域问题解决方法(2)——JSONP解决跨域

JSONP是什么?
JSON全称为JSON with Padding,是JSON的一种补充的使用方式,不是官方协议。

使用JSONP服务器后台要改动吗?
JSONP不同于一般的ajax请求返回json对象,JSONP返回的是script脚本。
所以,使用JSONP时,服务器后台需要进行改动,如果依然返回的是json对象,则会报错。

JSONP解决跨域的实现原理
浏览器只对XHR进行跨域问题校验,而JSONP的类型是script,所以可以回避跨域校验。
JSONP通过创建一个动态的script脚本,在script中把请求发出去。
注:请求后跟着一个下划线,是防止请求被缓存,如果允许缓存,则可以在ajax请求中加上cache: true

JSONP有什么弊端?
1.服务器需要改动代码支持
2.只支持get
3.发送的是script,不是XHR

综上所述:JSONP依然不是解决跨域最好的方法。


更多专业前端知识,请上 【猿2048】www.mk2048.com

angular解决跨域问题

angular解决跨域问题

在进行项目开发过程中,经常会遇到跨域问题,下面就通过一些配置进行解决跨域问题。

 

1.在项目根目录下进行创建文件 proxy.config.json;

{
    "/": {
        "target": "",//要指向的域名或端口号
        "logLevel": "debug",//
        "secure": false,//
        "changeOrigin": true,//
        "pathRewrite": {
            "^/": ""
        }
    }
}

  

2. 修改启动文件:

修改angular.json的配置文件:

{
      "projects": {
        "my-app": {
          "architect": {
            "serve": {
              "builder": "@angular-devkit/build-angular:dev-server","options": {
                "browserTarget": "my-app:build""proxyConfig": "proxy.config.json"
              },"configurations": {
                "production": {
                  "browserTarget": "my-app:build:production"
                }
              }
            }
          }
        }
      }
    }
}

 

不修改angula.json文件,修改package.json文件的start命令;

{
    "name": "my-app": {
        "ng": "ng""start": "ng serve --proxy-config proxy-config.json"
    }
}

 

总结

以上是小编为你收集整理的angular解决跨域问题全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

Flask + Nginx + React + Webpack 配置解决跨域问题

Flask + Nginx + React + Webpack 配置解决跨域问题

用 Flask 做后端开发单页应用,webpack-dev-server 生成静态文件在http://localhost:8080 下,Flask 页面在 http://localhost:5000 下。html 页面需要写成:

...
<script src="//localhost:8080/asserts/bundle.js"></script>
...

存在跨域问题,现用 nginx 将 80805000 端口代理到默认的 80 端口解决。看着也更优雅。

webpack 配置:

const url = "http://localhost:8080"

module.exports = {
    output: {
        filename: ''[name].js'',
        path: path.resolve(__dirname, ''dist''),
        publicPath: `${url}/asserts/`,
    },
    devServer: {
        port: 8080,
        compress: true,
        hot: true,
        historyApiFallback: true,
        contentBase: path.join(__dirname, "dist"),
        publicPath: `${url}/asserts/`,
    }
    ...
}

nginx 配置

server {
    listen 80;
    server_name localhost; 
    location / {
        # flask 代理
        proxy_pass http://127.0.0.1:5000;
    }

    location /asserts/ {
        # webpack-dev-server 代理
        proxy_pass http://127.0.0.1:8080/asserts/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        error_page 502 @start-webpack-dev-server;
    }

    location @start-webpack-dev-server {
        default_type text/plain;
        return 502 "Please start the webpack-dev-server first.";
    }
}

Flask-Cors:Python web应用程序中解决跨域问题

Flask-Cors:Python web应用程序中解决跨域问题

在开发web应用程序时,跨域问题是一个很常见的问题。由于浏览器的同源策略限制,请求的发出必须要在当前域名下发出,否则就会受到限制。这就造成了不同域名下服务器之间的数据交互变得非常困难。

为了解决这一问题,一种常用的方式是在服务器端做出相应的处理,即设置相应的跨域请求响应头。而Flask-Cors是一个优秀的解决跨域问题的Python库。

Flask-Cors是什么?

Flask-Cors是Flask扩展库中的一员,其主要功能是为Flask应用程序提供轻松解决跨域请求的功能。它可以让Flask应用程序支持跨域请求,并提供了简单易用的API,以便我们在代码中快速配置和调用。

如何使用Flask-Cors?

立即学习“Python免费学习笔记(深入)”;

在使用Flask-Cors之前,需要通过pip等包管理工具来安装Flask-Cors库。

接下来,在Flask应用程序中引用Flask-Cors并进行配置,可以使用以下代码:

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)

# 允许跨域请求
CORS(app, resources=r''/*'')

# 路由
@app.route(''/'')
def index():
    return jsonify(message=''Hello World!'')

# 启动服务器
if __name__ == ''__main__'':
    app.run()
登录后复制

使用CORS类创建一个新的CORS应用程序对象,通过传入Flask应用程序的实例app和允许跨域请求的资源列表来进行配置。在上面的例子中,我们设置了所有的资源都允许跨域请求。

除了以上代码,Flask-Cors还提供了其余的API用于更灵活地配置跨域请求响应头。

例如,我们还可以使用支持特定HTTP方法的CORS方法,如下所示:

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)

# 设置只支持GET、HEAD和OPTIONS方法的跨域请求
cors = CORS(app, resources={r''/api/*'': {''origins'': ''*''}, ''methods'': [''GET'', ''HEAD'', ''OPTIONS'']})

# 路由
@app.route(''/api/test'', methods=[''GET''])
def test():
    return jsonify(message=''Success!'')

# 启动服务器
if __name__ == ''__main__'':
    app.run()
登录后复制

在这里,我们指定了对“/api/*”路径下所有请求,且只限于GET、HEAD和OPTIONS这三种方法的跨域响应。

总结

Flask-Cors是一个非常优秀的解决Python web应用程序中跨域请求的扩展库。不仅提供了支持特定HTTP方法的跨域请求,还拥有很多灵活的API可供使用者进行配置。使用Flask-Cors能够极大地降低开发人员处理跨域问题的工作难度,提高开发效率。

以上就是Flask-Cors:Python web应用程序中解决跨域问题的详细内容,更多请关注php中文网其它相关文章!

关于Python | Flask 解决跨域问题flask跨域怎么解决的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于AJAX跨域问题解决方法(2)——JSONP解决跨域、angular解决跨域问题、Flask + Nginx + React + Webpack 配置解决跨域问题、Flask-Cors:Python web应用程序中解决跨域问题等相关内容,可以在本站寻找。

本文标签: