Warp框架中Cors Filter失效及OPTIONS请求返回405问题求助
Warp CORS过滤器失效且OPTIONS请求返回405 Method Not Allowed的解决方案
问题根源
你的代码中CORS过滤器仅附加在warp::get()的路由链上,而OPTIONS预检请求根本无法匹配这个GET路由,直接被Warp的路由匹配逻辑拒绝,返回405状态码,导致CORS过滤器完全没有机会处理OPTIONS请求。
修正方案
将CORS过滤器应用到所有路由的顶层,确保所有请求(包括OPTIONS)都能经过CORS过滤器处理。Warp的CORS实现会自动处理OPTIONS预检请求,无需手动添加OPTIONS路由。
修正后的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", "Content-Type", // 新增测试所需的Content-Type头 ]) .allow_methods(&[Method::PUT, Method::DELETE, Method::POST, Method::GET]) .build(); // 定义单个GET路由 let get_items = warp::get() .and(warp::path("questions")) .and(warp::path::end()) .and_then(get_questions); // 若有其他方法的路由(如PUT/POST),用.or()合并 // let put_items = warp::put() // .and(warp::path("questions")) // .and(warp::path::end()) // .and_then(put_question); // 合并所有路由后,统一应用CORS和日志过滤器 let routes = get_items // .or(put_items) .with(cors) .with(warp::log("cors test")); warp::serve(routes).run(([127, 0, 0, 1], 8000)).await; }
验证测试
执行你提供的curl命令:
curl -X OPTIONS localhost:8000/questions -v \ -H "Access-Control-Request-Method: PUT" \ -H "Access-Control-Request-Headers: content-type"
此时应返回200状态码,并包含正确的CORS响应头,示例响应如下:
* Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < access-control-allow-origin: * < access-control-allow-methods: PUT, DELETE, POST, GET < access-control-allow-headers: User-Agent, Sec-Fetch-Mode, Referer, Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Content-Type < access-control-max-age: 86400 < content-length: 0 < date: Wed, 01 Jan 2025 12:00:00 GMT
关键说明
- CORS过滤器必须应用到所有路由的合并结果上,而不是单个HTTP方法的路由链中,否则OPTIONS请求无法触发CORS逻辑。
- Warp的CORS实现会自动处理OPTIONS预检请求,无需手动编写OPTIONS路由处理逻辑。
内容的提问来源于stack exchange,提问作者egion
相关产品推荐
相关产品推荐

