rust 忽略扭曲中的Cors过滤器

xytpbqjk  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(223)

我正在学习Rust,并正在遵循Bastian Gruber link的学习Rust Webdevelopment(Manning)教程。我已经尝试了很多方法,但我不能让Cors过滤器,正如书中所概述的,真正做一些事情。它只是被忽略了。
此外,OPTIONS调用的应答为405 Method not Allowed。或者更准确地说,是拒绝(MethodNotAllowed)。
我试着从allow_methods()中删除Method::GET,但没有效果(get localhost:8000/questions仍然可以)。之前,我使用recover()向过滤器链添加了一个错误处理程序,以便检查始终为Rejection(MethodNotAllowed)的错误。我把它去掉了,这样例子就更短了。
另外,我尝试使用warp::OPTIONS()在过滤器链中显式地允许OPTIONS,但这只是返回get_questions()函数的结果,就像它是一个get请求一样。再次被忽略。
我的最小(非)工作示例:
main.rs:

use warp::{hyper::Method, Filter};

#[macro_use]
extern crate log;

async fn get_questions() -> Result<impl warp::Reply, warp::Rejection> {
    Ok(warp::reply::html("<p>There are no questions...</p>"))
}

#[tokio::main]
async fn main() {
    env_logger::init();
    info!("starting up");
    let cors = warp::cors()
        .allow_any_origin()
        .allow_headers(vec![
            "User-Agent",
            "Sec-Fetch-Mode",
            "Referer",
            "Origin",
            "Access-Control-Request-Method",
            "Access-Control-Request-Headers",
        ])
        .allow_methods(&[Method::PUT, Method::DELETE, Method::POST, Method::GET])
        .build();

    let get_items = warp::get()
        .and(warp::path("questions"))
        .and(warp::path::end())
        .and_then(get_questions)
        .with(cors)
        .with(warp::log("cors test"));

    warp::serve(get_items).run(([127, 0, 0, 1], 8000)).await;
}

Cargo.toml:

[package]
name = "cors_ignored"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
tokio = { version = "1.25", features = ["full"] }
warp = "0.3.3"
log = "0.4.0"
env_logger = "0.9.0"

测试cors的 curl :

curl -X OPTIONS localhost:8000/questions -v \
     -H "Access-Control-Request-Methods: PUT" \
     -H "Access-Control-Request-Headers: content-type"

编辑:正如建议的那样,我尝试使用warp::put()将端点定义为put而不是get。结果是一样的。OPTIONS请求会产生405“Method not allowed”,GET请求也是如此。PUT,路由允许的那个,产生一个Status 200和我的HTML代码片段。
同样按照建议,我添加了“Content-Type”来允许_headers,但行为保持不变。

uhry853o

uhry853o1#

1.使用不以s结尾的请求标头Access-Control-Request-Method
1.印前检查请求需要Origin标头。

curl -X OPTIONS localhost:8000/questions -v \
     -H "Access-Control-Request-Method: PUT" \
     -H "Access-Control-Request-Headers: content-type" \
     -H "Origin: https://foo.example"

相关问题