我正在编写一个简单的网络,其中 Rocket 作为后端,React 作为前端。
登录页面的代码片段如下所示
#[post("/login", data = "<data>")]
pub fn login(
conn: DbConn,
mut cookies: Cookies<'_>,
data: Form<LoginForm>,
) -> Result<JsonValue, NotFound<String>> {
let valid_account = match Account::find_by_email(&*conn, data.email.as_str()) {
Ok(account) => {
if account.password == data.password {
account
} else {
return Err(NotFound("Incorrect email or password!".to_string()));
}
}
Err(_) => return Err(NotFound("Incorrect email or password!".to_string())),
};
cookies.add_private(
Cookie::build(AUTH_COOKIE, valid_account.id.to_string())
.same_site(rocket::http::SameSite::Strict)
.finish(),
);
Ok(json!({
"email": valid_account.email,
"name": valid_account.name,
}))
}
代码main.rs
fn main() {
rocket::ignite()
.mount("/", routes![
account::login::login,
],
)
.register(catchers![errors::unauthorized])
.attach(rocket_cors::CorsOptions::default().to_cors().unwrap())
.manage(establish_connection())
.launch();
}
和尝试发送发布请求时的 React 代码
export const postForm = async (
pathUrl: string,
postInfo: { [name: string]: any }
) => {
let axiosConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*',
},
};
try {
const response = await axios.post(
baseUrl + pathUrl,
querystringify.stringify(postInfo),
axiosConfig
);
return response.data as CurrentUser;
} catch (err) {
console.log(err);
return Promise.reject(err.response);
}
};
如果我输入了正确的电子邮件和密码,该代码就可以正常工作。但是,如果我输入错误的凭据,它无法捕获错误消息。Rocket log 登录成功和登录失败是一样的,分别是
OPTIONS /login:
=> Error: No matching routes for OPTIONS /login.
=> Warning: Responding with 404 Not Found catcher.
=> CORS Fairing: Turned missing route OPTIONS /login into an OPTIONS pre-flight request
=> Response succeeded.
POST /login application/x-www-form-urlencoded:
=> Matched: POST /login (login)
=> Outcome: Success
=> Response succeeded.
我在浏览器中捕获的错误日志Error: "Request failed with status code 404"
不是在 post 函数中硬编码的预期错误消息。
我认为这可能与Rocket 内部有关Option
或preflight
处理,这可能是出于安全目的。但是我怎样才能抑制系统错误并让我的代码接管呢?
我已经阅读了之前的 SO 帖子,例如state undefined: while 从 react 应用程序和 GitHub 问题发送帖子请求,例如https://github.com/SergioBenitez/Rocket/issues/25。仍然找不到我的问题的答案。
提前致谢!