首页 > 解决方案 > 如何正确提取请求参数的值?

问题描述

前端有一个请求代码:

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/

但是在它的帮助下不可能完成必要的任务。
(有些例子给出了编译器错误——有些例子对我来说并不完全清楚它们的作用原理。)
我想看看获得这个值的最原始的方法,从 ..

标签: rustactix-web

解决方案


前端代码有错误。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-web3.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
}

推荐阅读