How do I correctly pull out the value of the request parameter?

Viewed 174

There is a request code from the frontend:

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);
});

On the backend, data is received as follows:

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
}



Question:
How, on the backend, I can pull out the foo: perfectGoods value passed from the frontend?

I tried to try different examples from this manual:
https://actix.rs/docs/extractors/

But it was not possible to accomplish the necessary task with the help of it.
(Some examples give a compiler error - some are not completely clear to me on what principle they function.)
I would like to see the most primitive way of getting this value, to begin with ..

1 Answers

There is an error in the frontend code. HTTP Content-Type: application/x-www-form-urlencoded is for form posts not gets.

Frontend using a Post request:

// 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);
});

Or Frontend using a Get request:

// 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);
});

Then use the web::Form extractor to get the foo parameter from post requests and web::Query to get the foo parameter from get requests.

Here is the backend that supports both post/get requests. Tested with the latest actix-web 3.0.0 release.

Cargo.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
}
Related