[英]How do I get the parameters from a POST request from a HTML form in Actix-web?
I am building a little webapp in Actix-web, but I can't find any example of getting parameters out of a POST request in Actix-web anywhere. 我正在Actix-web中构建一个小的webapp,但我找不到任何从Actix-web中的POST请求中获取参数的示例。
Searching their excellent examples repo only gives a couple of (to me) meaningful examples , but they both deal with JSON and not form data. 搜索他们优秀的例子repo只给出了几个 (对我而言)有意义的例子 ,但它们都处理JSON而不是表单数据。
I also found this page , which I suspect holds the answer; 我也找到了这个页面 ,我怀疑它是答案; but to a beginner this isn't much help. 但对于初学者来说,这并没有多大帮助。
I imagine it should look something like: 我想它应该看起来像:
<form method="POST">
<input type="password" name="password">
<button type="submit">Login</button>
</form>
and 和
fn main() {
// ...
App::with_state(AppState { db: pool.clone() })
.middleware(IdentityService::new(
CookieIdentityPolicy::new(&[0; 32])
.name("auth-cookie")
.secure(true),
))
.resource("/login", |r| {
r.method(http::Method::GET).with(login);
r.method(http::Method::POST).with(perform_login) // help!
})
}
struct LoginParams {
password: String,
}
fn perform_login(mut req: HttpRequest<AppState>, params: LoginParams) -> HttpResponse {
if params.password == "abc123" {
req.remember("logged-in".to_owned());
// redirect to home
};
// show "wrong password" error
}
You can use an extractor by: 您可以通过以下方式使用提取器:
Form
as Nikolay said , with the type parameter of your struct. 在您的情况下,使用Form
作为Nikolay说 ,使用结构的类型参数。 If you take a look at simple example in linked documentation you'll see how describe such handler. 如果你看一下链接文档中的简单示例,你会看到如何描述这样的处理程序。
Here is a bit more complete one: 这里有一个更完整的一个:
#[derive(Deserialize)]
struct AddHook {
id: u64,
title: String,
version: Option<String>,
code: Option<String>
}
fn remove_hook_del((query, state): (Form<AddHook>, State<AppState>)) -> FutureHttpResponse {
let query = query.into_inner();
let AddHook {id, title, version, code} = query;
//Do something with your data
}
App::with_state(AppState::new()).resource("/remove_hook", |res| {
res.method(Method::GET).with(remove_hook_get);
res.method(Method::DELETE).with(remove_hook_del);
res.route().f(not_allowed);
})
This is more or less a complete example for the current master branch of actix-web
. 这或多或少是actix-web
当前主分支的完整示例。 I also made it with state to show how you can use multiple arguments in your handler 我还使用state来显示如何在处理程序中使用多个参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.