Actix Web 不处理 post 请求?

Alc*_*ist 6 rust actix-web

因此,我尝试创建一个基本的 actix-web 应用程序,它允许我创建一个非常基本的博客系统。它正在处理我的 GET 请求,但不处理我的 POST 请求。

主要.rs:

use actix_web::{HttpServer, App, web};
use sqlx::postgres::PgPool;
use dotenv::dotenv;

mod posts;
mod database;

#[actix_web::main]
pub async fn main() -> std::io::Result<()>{
    dotenv().ok();

    let pool = PgPool::connect(&dotenv::var("DATABASE_URL").unwrap()).await.unwrap();

    HttpServer::new(move || {
        // The scope for all post services
        let posts = web::scope("/posts").service(posts::get_all_posts).service(posts::create_post);

        App::new()
            .data(pool.clone())
            .service(web::scope("/api").service(posts))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}
Run Code Online (Sandbox Code Playgroud)

帖子/routes.rs:

use super::*;
use database::{NewPost, model::Post};
use actix_web::{get, post, Responder, HttpResponse};

#[get("/")]
pub async fn get_all_posts(pool: web::Data<PgPool>) -> impl Responder {
    println!("New GET request for all posts!");
    let result = Post::find_all(pool.get_ref()).await;

    match result {
        Ok(posts) => HttpResponse::Ok().json(posts),
        _ => HttpResponse::BadRequest().body("Error trying to read all the posts from the database") 
    }
}

#[post("/new")]
pub async fn create_post(post: web::Json<NewPost>, pool: web::Data<PgPool>) -> impl Responder {
    println!("New POST request to create a post!");
    let result = Post::new_post(post.into_inner(), pool.as_ref()).await;

    match result {
        Ok(post) => HttpResponse::Ok().json(post),
        _ => HttpResponse::BadRequest().body("Error trying to create a new post")
    }
}
Run Code Online (Sandbox Code Playgroud)

数据库/模型.rs:

use serde::{Serialize, Deserialize};
use sqlx::{FromRow, PgPool, Row, postgres::PgRow};
use uuid::Uuid;
use chrono::prelude::*;

/// Struct to represent database record.
#[derive(Serialize, FromRow, Debug)]
pub struct Post {
    pub id: Uuid,
    pub content: String,
    pub created_at: chrono::NaiveDateTime
}

/// Struct to receive user input.
#[derive(Serialize, Deserialize)]
pub struct NewPost {
    pub content: String
}

impl Post {
    pub async fn find_all(pool: &PgPool) -> std::io::Result<Vec<Post>> {
        let mut posts = Vec::new();
        let recs = sqlx::query_as!(Post, r#"SELECT id, content, created_at FROM post ORDER BY id"#)
            .fetch_all(pool)
            .await
            .unwrap();

        for rec in recs {
            posts.push(Post {
                id: rec.id,
                content: rec.content,
                created_at: rec.created_at
            });
        }

        Ok(posts)
    }

    pub async fn new_post(post: NewPost, pool: &PgPool) -> std::io::Result<Post> {
        let mut tx = pool.begin().await.unwrap();
        let post = sqlx::query("INSERT INTO post (id, content, created_at) VALUES ($1, $2, $3) RETURNING id, content, created_at")
            .bind(Uuid::new_v4())
            .bind(post.content)
            .bind(Utc::now())
            .map(|row: PgRow| {
                Post {
                    id: row.get(0),
                    content: row.get(1),
                    created_at: row.get(2)
                }
            })
            .fetch_one(&mut tx)
            .await
            .unwrap();

        tx.commit().await.unwrap();
        Ok(post)
    }
}
Run Code Online (Sandbox Code Playgroud)

目前,我正在使用curl 来测试API。当我想发送 GET 请求时,我使用以下命令:

curl localhost:8080/api/posts/
Run Code Online (Sandbox Code Playgroud)

当我运行此命令时,我的 Rust 应用程序会打印出以下语句:“针对所有帖子的新 GET 请求!” 正如我所期望的那样。

当我想发送 POST 请求时,我使用以下命令:

curl -H "Content-Type: application/json" -X POST -d '{ \
    "content": "This is my first post" \
}' localhost:8080/api/posts/new
Run Code Online (Sandbox Code Playgroud)

运行这个curl命令后,我根本没有得到任何输出,curl终端没有任何输出,我的rust程序也没有任何输出。

Val*_*tin 3

只要仔细阅读所有内容,你的卷发实际上可能是罪魁祸首。

如果您添加-i显示响应标头,那么您可以看到您实际上收到了 400 Bad Request。

$ curl -i -H "Content-Type: application/json" -X POST -d '{ \
>     "content": "This is my first post" \
> }' localhost:8080/api/posts/new
HTTP/1.1 400 Bad Request
content-length: 0
date: Sun, 03 Jan 2021 14:04:12 GMT
Run Code Online (Sandbox Code Playgroud)

如果您更改create_post为 takepost: String而不是post: web::Json<NewPost>,则可以更轻松地检查端点正在接收的有效负载。

pub async fn create_post(post: String) -> impl Responder {
    println!("{}", post);
Run Code Online (Sandbox Code Playgroud)

现在执行相同的操作curl会显示以下输出:

{ \
    "content": "This is my first post" \
}
Run Code Online (Sandbox Code Playgroud)

简而言之,问题在于反斜杠保留在有效负载中。因此,要使其正常工作,您唯一需要做的就是删除反斜杠。

{ \
    "content": "This is my first post" \
}
Run Code Online (Sandbox Code Playgroud)