在发送fetch之前,浏览器将发送一个请求方法OPTIONS,以确认该API将接受来自具有特定来源的脚本的请求。
Chrome显示我的Axum服务器拒绝了我客户405的请求。我的路由器看起来像这样:
let app = Router::new()
.layer(TraceLayer::new_for_http())
.layer(CorsLayer::permissive())
.route("/api", post(server));路由器::层表示,对路由器的所有请求都将由该层的相应中间件处理。但我不确定它能做好它的工作。
发布于 2022-08-26 08:59:48
.layer()函数是一个构建器,因此返回一个新的Router,并封装内部路由器。将首先测试路由/api,然后拒绝405,因为只支持请求方法POST,而不是OPTIONS。
总之,您需要您的CorsLayer“在您的路由之外”,以便它能够响应OPTIONS请求。
请注意文档中的示例:
// All requests to `first_handler` and `second_handler` will be sent through
// `ConcurrencyLimit`
let app = Router::new().route("/", get(first_handler))
.route("/foo", get(second_handler))
.layer(ConcurrencyLimitLayer::new(64))
// Request to `GET /bar` will go directly to `third_handler` and
// wont be sent through `ConcurrencyLimit`
.route("/bar", get(third_handler));顺便说一句,您的TraceLayer没有跟踪您的API调用,原因是相同的!
尝试以下操作,您将看到OPTIONS请求被记录下来,POST应该会按下您的server
let app = Router::new()
.route("/api", post(server))
.layer(CorsLayer::permissive())
.layer(TraceLayer::new_for_http());https://stackoverflow.com/questions/73498537
复制相似问题