草庐IT

关于reactjs:Python Falcon和Axios:无法允许CORS

codeneng 2023-03-28 原文

Python Falcon and Axios: Unable to allow CORS

我在允许向 Flask 服务器发出 CORS 请求时遇到了困难。客户端是使用 axios 的 React。客户端的错误是:

1
Access to XMLHttpRequest at <url> has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

如果我直接在浏览器中导航到 url(在任一 PC 上),它加载没有问题。但是当使用 axios 时它会中断。

我尝试了以下策略:

1) 直接追加头部:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from wsgiref.simple_server import make_server
import falcon
import transform
import json
import engine

index = transform.reindex()
app = falcon.API()

class Search:
    def on_get(self, request, response):
        query = request.params['searchText']
        result = engine.search(query, index)

        response.append_header('access-control-allow-origin', '*')
        response.status = falcon.HTTP_200
        response.body = json.dumps(result)

search = Search()
app.add_route('/search', search)

if __name__ == '__main__':
    with make_server('', 8003, app) as httpd:
        print('Serving on port 8003...')
        httpd.serve_forever()

2) 通过中间件全局使用 falcon_cors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from wsgiref.simple_server import make_server
import falcon
from falcon_cors import CORS    
from flask import jsonify
import transform
import json
import engine


cors = CORS(allow_origins_list=[
    '<client ip>'
    ])

index = transform.reindex()
app = falcon.API(middleware=[cors.middleware])


class Search:
    def on_get(self, request, response):
        query = request.params['searchText']
        result = engine.search(query, index)


        response.status = falcon.HTTP_200
        response.body = json.dumps(result)


search = Search()

app.add_route('/search', search)

if __name__ == '__main__':
    with make_server('', 8003, app) as httpd:
        print('Serving on port 8003...')
        httpd.serve_forever()

1) 在本地使用 falcon-cors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from wsgiref.simple_server import make_server
import falcon

from falcon_cors import CORS


from flask import jsonify
import transform

import json
import engine


cors = CORS(allow_origins_list=['*'])

index = transform.reindex()
app = falcon.API(middleware=[cors.middleware])

public_cors = CORS(allow_all_origins=True)

class Search:
    cors = public_cors
    def on_get(self, request, response):
        query = request.params['searchText']

        response.status = falcon.HTTP_200
        response.body = json.dumps(result)


search = Search()

app.add_route('/search', search)


if __name__ == '__main__':
    with make_server('', 8003, app) as httpd:
        print('Serving on port 8003...')
        httpd.serve_forever()

没有任何工作。当我在浏览器中检查响应时,我可以看到 \\'access-control-allow-origin\\': \\'*\\' 我在某处读到 axios 不能总是看到所有标题。有没有人遇到过这个?谢谢。


可能的情况-

当使用浏览器时,如果服务器需要它,它会在您的请求中附加 withCredentials: true。但是对于 Angular 或 React,您必须在 httpOptions.

中明确提供 withCredentials: true

我建议您使用 Falcon 或 Flask。
如果仅在 gunicorn 或 waitress 下使用 Falcon,以下过程可能会有所帮助-

获取猎鹰-cors

1
from falcon_cors import CORS

有一些列入白名单的方法。

1
2
3
4
5
6
7
8
9
10
# Methods supported by falcon 2.0.0
# 'CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE'

whitelisted_methods = [
   "GET",
   "PUT",
   "POST",
   "PATCH",
   "OPTIONS" # this is required for preflight request
]

了解有关预检请求的更多信息。

搜索类如下

1
2
3
4
5
6
7
class Search:

    def on_get(self, req, resp):
        response_obj = {
           "status":"success"
        }
        resp.media = response_obj

有一些列入白名单的来源。

1
2
3
4
whitelisted_origins = [
   "http://localhost:4200",
   "https://<your-site>.com"
]

在中间件中添加 cors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
cors = CORS(
    # allow_all_origins=False,
    allow_origins_list=whitelisted_origins,
    # allow_origins_regex=None,
    # allow_credentials_all_origins=True,
    # allow_credentials_origins_list=whitelisted_origins,
    # allow_credentials_origins_regex=None,
    allow_all_headers=True,
    # allow_headers_list=[],
    # allow_headers_regex=None,
    # expose_headers_list=[],
    # allow_all_methods=True,
    allow_methods_list=whitelisted_methods
)

api = falcon.API(middleware=[
    cors.middleware,
    # AuthMiddleware()
    # MultipartMiddleware(),
])

现在你可以为你的班级添加路线了。

1
2
from src.search import SearchResource
api.add_route('/search', SearchResource())

供您参考,如果传入请求中有withCredentials: true,请确保不要错过上面cors中设置为whitelisted_originsallow_credentials_origins_list

如果要允许凭据,则不应将 allow_all_origins 设置为 True。您必须在 allow_credentials_origins_list.

中指定确切的协议域端口

有关关于reactjs:Python Falcon和Axios:无法允许CORS的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  3. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  4. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  5. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  6. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

  7. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  8. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  9. ruby-on-rails - RSpec:避免使用允许接收的任何实例 - 2

    我正在处理旧代码的一部分。beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)endRubocop错误如下:Avoidstubbingusing'allow_any_instance_of'我读到了RuboCop::RSpec:AnyInstance我试着像下面那样改变它。由此beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)end对此:let(:sport_

  10. ruby-on-rails - 无法让 rspec、spork 和调试器正常运行 - 2

    GivenIamadumbprogrammerandIamusingrspecandIamusingsporkandIwanttodebug...mmm...let'ssaaay,aspecforPhone.那么,我应该把“require'ruby-debug'”行放在哪里,以便在phone_spec.rb的特定点停止处理?(我所要求的只是一个大而粗的箭头,即使是一个有挑战性的程序员也能看到:-3)我已经尝试了很多位置,除非我没有正确测试它们,否则会发生一些奇怪的事情:在spec_helper.rb中的以下位置:require'rubygems'require'spork'

随机推荐