rust - 如何正确提取请求参数的值?
问题描述
前端有一个请求代码:
return axios.get("http://127.0.0.1:8088/mike" , {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
params: {
foo: 'perfectGoods'
}
})
.then(response => {
console.log(JSON.stringify(response));
})
.catch(function (error) {
console.log(error);
});
在后端,接收到的数据如下:
use actix_cors::Cors;
use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer, Result};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct MyObj {
name: String,
}
async fn index(obj: web::Path<MyObj>) -> Result<HttpResponse> {
Ok(HttpResponse::Ok().json(MyObj {
name: obj.name.to_string(),
}))
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer};
HttpServer::new(|| App::new()
.wrap(
Cors::new() // <- Construct CORS middleware builder
.allowed_origin("http://localhost:3000")
.allowed_methods(vec!["GET", "POST"])
.allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
.allowed_header(http::header::CONTENT_TYPE)
.max_age(3600)
.finish())
.service(
web::resource("")
.route(web::get().to(index))
.route(web::head().to(|| HttpResponse::MethodNotAllowed())
))
.route(r"{name}", web::get().to(index)))
.bind("127.0.0.1:8088")?
.run()
.await
}
问题:
如何在后端提取foo: perfectGoods
从前端传递的值?
我尝试尝试本手册中的不同示例:
https ://actix.rs/docs/extractors/
但是在它的帮助下不可能完成必要的任务。
(有些例子给出了编译器错误——有些例子对我来说并不完全清楚它们的作用原理。)
我想看看获得这个值的最原始的方法,从 ..
解决方案
前端代码有错误。HTTPContent-Type: application/x-www-form-urlencoded
用于未获取的表单帖子。
使用 Post 请求的前端:
// post request
axios.post("http://127.0.0.1:8088/mike" , {
foo: 'perfectGoods'
})
.then(response => {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
或使用 Get 请求的前端:
// get request
return axios.get("http://127.0.0.1:8088/mike" , {
params: {
foo: 'perfectGoods'
}
})
.then(response => {
console.log(JSON.stringify(response));
})
.catch(function (error) {
console.log(error);
});
然后使用web::Form
提取器foo
从 post 请求web::Query
中获取foo
参数,并从 get 请求中获取参数。
这是支持 post/get 请求的后端。使用最新的actix-web
3.0.0 版本进行测试。
货运.toml
[package]
name = "web_form"
version = "0.1.0"
edition = "2018"
[dependencies]
actix-web = "3.0.1"
actix-cors = "0.3.0"
serde = "1.0.116"
actix-rt = "1.1.1"
env_logger = "0.7.1"
src/main.rs
use actix_cors::Cors;
use actix_web::{http, web, get, post, App, HttpResponse, HttpServer, Result};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct MyObj {
name: String,
}
#[derive(Serialize, Deserialize, Clone)]
struct MyParams {
foo: Option<String>,
}
#[derive(Serialize, Deserialize)]
struct MyResponseObj {
name: String,
params: MyParams,
}
#[get("/{name}")]
async fn index_get(path: web::Path<MyObj>, params: web::Query<MyParams>) -> Result<HttpResponse> {
Ok(HttpResponse::Ok().json(MyResponseObj {
name: path.name.to_string(),
params: params.clone(),
}))
}
#[post("/{name}")]
async fn index_post(path: web::Path<MyObj>, params: web::Json<MyParams>) -> Result<HttpResponse> {
Ok(HttpResponse::Ok().json(MyResponseObj {
name: path.name.to_string(),
params: params.clone(),
}))
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new()
.wrap(
Cors::new() // <- Construct CORS middleware builder
.allowed_origin("http://localhost:3000")
.allowed_methods(vec!["GET", "POST"])
.allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
.allowed_header(http::header::CONTENT_TYPE)
.max_age(3600)
.finish())
.service(index_get)
.service(index_post)
)
.bind("127.0.0.1:8088")?
.run()
.await
}
推荐阅读
- sas - 有条件地执行宏功能
- acumatica - 如何使 AP 发票行中的税务类别字段为必填项,但仍更新明细总计和余额
- ansible - 如何每 5 分钟将输出打印到 Travis
- r - 减轻斐波那契 while 循环
- java - JPA:如何仅覆盖 @Embedded 属性的列名
- azure - 如何为 AKS 群集永久设置 Azure 空闲超时?
- java - 将 SQL Server 的 BULK INSERT 与 EntityManager 的 createNativeQuery 一起使用会导致 TransactionRequiredException
- python - Python - 通过 UDP 接收
- boto3 - 如何以编程方式为 AWS EC2 实例指定初始磁盘大小
- matrix - 在前 K 个左右向量的子空间相同的约束下,如何解决 SVD 问题?