【问题标题】:How works Json<T> (Form data does not have form content type)Json<T> 工作原理(表单数据没有表单内容类型)
【发布时间】:2019-06-09 07:58:24
【问题描述】:

我对 Rust 完全陌生。我正在尝试用 Rocket 创建一个非常简单的 API。 我的以下路线不起作用,我不知道为什么。

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use] extern crate rocket;

use rocket_contrib::json::Json;
use serde::{Serialize, Deserialize};
use serde_json::Result as JsonResult;

#[derive(Serialize, Deserialize)]
struct Article {
    id: usize,
    title: String,
    body: String,
}

#[post("/new", format = "application/json", data = "<article>")]
fn create_article (article: Json<Article>) -> JsonResult<()> {
    println!("Article is: id:{}, title:{}, body:{}", article.id, article.title, article.body);
    Ok(())
}

fn main() {
    rocket::ignite()
    .mount("/article", routes![create_article])
    .launch();
}

当我发送请求时,我有以下内容:

POST /article/new?id=1&title=titre&body=corps application/json:
    => Matched: POST /article/new (create_article)
    => Warning: Form data does not have form content type.
    => Outcome: Forward
    => Error: No matching routes for POST /article/new?id=1&title=titre&body=corps application/json.
    => Warning: Responding with 404 Not Found catcher.
    => Response succeeded.

有人可以帮我吗?

【问题讨论】:

    标签: rust serde rust-rocket


    【解决方案1】:

    您通过在 URL 中提供参数来请求 POST 端点,例如 GET 端点。使用curl 尝试以下操作:

    curl -d '{"id": 1, "title": "titre", "body": "corps"}' -H "Content-Type: application/json" -X POST http://localhost:8000/article/new
    

    【讨论】:

    • 是的,我是因为失眠。但是使用 curl 命令我有相同的行为。
    • 你能再检查一遍吗?我在我的计算机上编译并执行了相同的代码,没有任何问题。看一看:i.imgur.com/uLZA5L4.png
    • 我创建了一个新项目,复制粘贴我的代码....它可以工作,但不能在我的旧项目上运行.. 奇怪。谢谢!
    猜你喜欢
    • 2022-11-12
    • 2021-02-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多