【问题标题】:How do I configure actix-web to accept CORS requests from any origin?如何配置 actix-web 以接受来自任何来源的 CORS 请求?
【发布时间】:2019-12-16 22:20:09
【问题描述】:

我正在使用 actix-web 构建一个 REST API。如何配置 CORS 以接受来自任何来源的请求?

Cors::new() // <- Construct CORS middleware builder
    .allowed_origin("localhost:8081")
    .allowed_methods(vec!["GET", "POST"])
    .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
    .allowed_header(http::header::CONTENT_TYPE)
    .max_age(3600)

上面的代码在localhost:8081 的网络上工作,但不是来自0.0.0.0:8081127.0.0.1:8081。我尝试"*" 允许所有人,但它不起作用。如何允许所有,或至少允许特定来源,然后传递多个 URL?

【问题讨论】:

    标签: rust cors rust-actix actix-web


    【解决方案1】:

    默认All起源是allowed

    这是我的简单 CORS 设置(允许所有来源和方法 + 允许发送凭据)

    Cors::new().supports_credentials() 
    

    您可以从它开始,逐步禁止方法、来源和标头。

    【讨论】:

    • 这很好,我想允许所有人。如果我想特别允许 3 个网址怎么办?比如,abc.com、abc.uk、abc.org?
    • 在每个允许的来源上链式调用allowed_origin
    • 我得到 error[E0599]: no function or associated item named new found for struct Cors in the current scope
    • @EvanCarroll 似乎 actix-core 已更新 - 使用 Cors::default() 并查看实际文档 docs.rs/actix-cors/0.5.4/actix_cors/struct.Cors.html
    • 要对最新版本(当前为 0.5.4)执行相同操作,请使用 Cors::permissive()
    猜你喜欢
    • 2020-11-18
    • 2019-08-11
    • 2021-04-08
    • 1970-01-01
    • 2022-01-21
    • 2021-12-31
    相关资源
    最近更新 更多