繁体   English   中英

从React应用发送POST请求到Rocket后端时出错

[英]Error sending POST request from React app to Rocket backend

我尝试从单页应用程序发出POST请求时遇到404错误,即使该路由在Postman中也有效。

路由

#[post("/letters", format = "application/json", data = "<new_letter>")]
fn write_letter(new_letter: Json<NewLetter>, conn: DbConn) -> Json<Value> {
    Json(json!({
        "status": Letter::write(new_letter.into_inner(), &conn),
        "result": null
    }))

}

我已经设置main.rs以允许CORS

let (allowed_origins, failed_origins) = AllowedOrigins::some(&["http://localhost:3000"]);
let options = rocket_cors::Cors {
    allowed_origins: allowed_origins,
    allowed_methods: vec![Method::Get, Method::Put, Method::Post, Method::Delete]
        .into_iter()
        .map(From::from)
        .collect(),
    allowed_headers: AllowedHeaders::all(),
    allow_credentials: true,
    ..Default::default()
};

所有路由都可以在Postman中使用,而GET请求可以在我的应用程序中使用。 但是,当我尝试从应用程序发出POST请求时,我在前端收到404,并从后端记录以下内容:

OPTIONS /api/letters:
=> Error: No matching routes for OPTIONS /api/letters.
=> Warning: Responding with 404 Not Found catcher.
=> CORS Fairing: Turned missing route OPTIONS /api/letters into an OPTIONS pre-flight request
=> Response succeeded.

这是我的前端供参考:

writeLetter: (letter) => axios.post(`${base_url}/api/letters`, letter)
  .then(res => {
     if (res.status == 201) {
      console.log("letter successfully submitted")
      return res
    }
    throw new Error(res.error)
  }),

我实现Axios或rocket_cors的方式有问题吗? 我发现了一个类似的问题,但似乎配置正确。

我认为我对OPTIONS路由日志的方式不满意。 我以为它正在向前端发送404响应,因为“ Warning: Responding with 404 Not Found catcher Response succeeded行但在其下面的两行表示Response succeeded因此我在DevTools中进行了更深入的研究。

选项发送回200响应,并且由于我只考虑了创建的201响应,因此引发了错误。

我将我的API更新为

if (res.status == 201 || res.status == 200) {
  console.log("letter successfully submitted")
  return res
}

从而避免了引发错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM