我是rust和火箭框架的初学者。我正在构建一个简单的登录应用程序,它需要用户的详细信息,并将其存储在数据库中。但是我似乎不知道如何从HTML表单接收数据。
我看到:https://rocket.rs/v0.5-rc/guide/requests/#forms根据我编写的代码。我的代码:main.rs
use rocket::*;
use rocket::response::content::RawHtml;
use rocket::http::RawStr;
use rocket::form::Form;
#[get("/")]
fn index() -> RawHtml<&'static str> {
RawHtml(include_str!("templates/index.html"))
}
#[derive(FromForm)]
struct UserInput<'r> {
r#type: &'r str,
}
// #[post("/create_account", data = "<userdata>")]
// fn create_account(user_input: Form<UserInput>) -> RawHtml<&'static str> {
// print(format!("Your value: {}", user_input.value));
// return RawHtml(include_str!("templates/account.html", messages = messages))
// }
//use rocket::form::Form;
#[derive(FromForm)]
#[derive(Debug)]
struct user_input<'r> {
r#type: &'r str,
}
#[post("/create_account", data = "<task>")]
fn create_account(task: Form<user_input<'_>>) -> RawHtml<&'static str> {
println!("{:#?}",task);
return RawHtml(include_str!("templates/account.html"))
}
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
sql::setup();
let _rocket = rocket::build()
.mount("/", routes![index])
.mount("/", routes![create_account])
// .mount("/confirmation", routes![confirmation])
.launch()
.await?;
Ok(())
}
HTML表单文件:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Account Creation</h1>
<br>
<h2>User Details</h2>
<form action="/create_account" method="post">
<!-- name, age, email, phno, password -->
<label for="Name">Name (Enter Full Name)</label>
<br>
<input type="text" name="Name" id="Name" text="Name">
<br>
<label for="age">Age</label>
<br>
<input type="number" name="age" id="age">
<br>
<label for="email">BCBS outlook email</label>
<br>
<input type="email" name="email" id="email" text="BCBS outlook email">
<br>
<label for="phno">Phone Number</label>
<br>
<input type="tel" name="phno" id="phno">
<br>
<label for="password">Password</label>
<br>
<input type="password" name="password" id="password">
<br> <br>
<input type="submit" value="Create Account">
</form>
</body>
</html>
Thanks in advance
在你的输入元素中使用小写的名字
<input type="text" name="name" id="name">
你可以在你的rust代码中使用这些字段。
#[derive(FromForm)]
struct CreateAccount {
name: String,
}
#[post("/create_account", data = "<account>")]
fn create_account(account: Form<CreateAccount>) -> RawHtml<&'static str> {
println!("{:#?}",account.name);
return RawHtml(include_str!("templates/account.html"))
}