gpt4 book ai didi

rust - Actix Web是否不处理发布请求?

转载 作者:行者123 更新时间:2023-12-03 11:44:12 26 4
gpt4 key购买 nike

因此,我正在尝试创建一个基本的actix-web应用程序,该应用程序将允许我创建一个非常基本的博客系统。它正在处理我的GET请求,但没有处理我的POST请求。
main.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
}
posts/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")
}
}
数据库/model.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)
}
}
目前,我正在使用curl来测试API。当我要发送GET请求时,请使用以下命令:
curl localhost:8080/api/posts/
当我运行此命令时,我的rust应用程序将打印出以下语句:“所有帖子都需要新的GET请求!”就像我期望的那样。
当我要发送POST请求时,请使用以下命令:
curl -H "Content-Type: application/json" -X POST -d '{ \
"content": "This is my first post" \
}' localhost:8080/api/posts/new
运行此curl命令后,我什么也没有得到,curl终端也没有任何输出,而rust程序也没有任何输出。

最佳答案

仅阅读所有内容,您的卷发实际上可能是罪魁祸首。
如果包含-i来显示响应 header ,则可以看到实际上收到了400错误请求。

$ 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
如果将 create_post更改为 post: String而不是 post: web::Json<NewPost>,则可以更轻松地检查端点接收的有效负载。
pub async fn create_post(post: String) -> impl Responder {
println!("{}", post);
现在执行相同的 curl将显示以下输出:
{ \
"content": "This is my first post" \
}
简而言之,问题在于反斜杠保留在有效负载中。因此,要使其正常工作,唯一需要做的就是删除反斜杠。
curl -H "Content-Type: application/json" -X POST -d '{
"content": "This is my first post"
}' localhost:8080/api/posts/new

关于rust - Actix Web是否不处理发布请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65550182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com