尝试从单页应用程序发出 POST 请求时出现 404 错误,即使该路由在 Postman 中有效。
路线.rs
#[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 有问题吗?我发现了一个类似的问题,但我似乎正确配置了它。