如何在Rocket Rust REST API中将X-Total-Count添加到标头响应中?

如何在Rocket Rust REST API中将X-Total-Count添加到标头响应中?,rust,react-admin,rust-rocket,Rust,React Admin,Rust Rocket,我用Rust创建了一个RESTAPI,它可以与swagger一起工作。 现在,我试图使用这个API,精确地说,使用React。一切正常,直到我需要调用一个列表,其中出现了著名的X-Total-Count问题,我无法解决它,可能是因为缺乏生锈的经验 这就是信息 HTTP响应中缺少X-Total-Count头。jsonServer数据提供程序要求资源列表的响应包含此头以及生成分页的结果总数。如果使用CORS,是否在访问控制公开头中声明了X-Total-Count 这是我的回复标题 HTTP/1.1

我用Rust创建了一个RESTAPI,它可以与swagger一起工作。 现在,我试图使用这个API,精确地说,使用React。一切正常,直到我需要调用一个列表,其中出现了著名的X-Total-Count问题,我无法解决它,可能是因为缺乏生锈的经验

这就是信息 HTTP响应中缺少X-Total-Count头。jsonServer数据提供程序要求资源列表的响应包含此头以及生成分页的结果总数。如果使用CORS,是否在访问控制公开头中声明了X-Total-Count

这是我的回复标题

HTTP/1.1 200 OK
Content-Type: application/json
Server: Rocket
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Expose-Headers: x-total-count, content-length, server
Content-Length: 45
Date: Wed, 02 Jun 2021 04:38:21 GMT
我尝试了很多方法,在标题中添加X-Total-Count:cant\u registries with out any lucky

这是我的主要工作。欢迎任何提示、帮助和修改。提前谢谢

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_okapi;

use rocket::request::Request;
use rocket::response::{self, Response, Responder};
use rocket::http::ContentType;
use rocket::http::Header;

use rocket::request::{Form, FromForm};
use rocket_contrib::json::Json;
use rocket_okapi::swagger_ui::*;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use rocket::http::Method;
use std::env;
use std::process::Command;
use rocket_cors::{
    AllowedOrigins,
    Cors, CorsOptions,
};

#[derive(Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
struct User {
    user_id: u64,
    username: String
}

// impl<'r> Responder<'r> for User {
//    fn respond_to(self, _: &Request) -> response::Result<'r> {
//        Response::build()
//            .header(Header::new("X-Total-Count", "1"))
//            .ok()
//    }
// }

fn example_email() -> &'static str {
    "test@example.com"
}

fn make_cors() -> Cors {
    let allowed_origins = AllowedOrigins::some_exact(&[
        "http://localhost:3000",
    ]);

    CorsOptions { // 5.
        allowed_origins,
        expose_headers: [ "x-total-count", "content-length","server" ]
        .iter()
            .map(ToString::to_string)
            .collect(), 
        allowed_methods: vec![Method::Get, Method::Post, Method::Patch].into_iter().map(From::from).collect(),
        allow_credentials: false,
        ..Default::default()
    }
        .to_cors()
        .expect("error while building CORS")
}

/// # Get all users
#[openapi]
#[get("/user")]
fn get_all_users() -> Json<Vec<User>> {
    Json(vec![User {
        user_id: 88,
        username: "goja288".to_owned(),
    }])
    

}

fn main() {
    rocket::ignite()
        .mount(
            "/",
            routes_with_openapi![
                get_all_users,
            ],
        )
        .mount(
            "/swagger-ui/",
            make_swagger_ui(&SwaggerUIConfig {
                url: "../openapi.json".to_owned(),
                ..Default::default()
            }),
        ).attach(make_cors())
        .launch();
}
#![功能(过程宏、数据宏)]
#[宏_使用]
外部板条箱火箭;
#[宏_使用]
外部板条箱火箭_okapi;
使用rocket::request::request;
使用rocket::response::{self,response,Responder};
使用rocket::http::ContentType;
使用rocket::http::Header;
使用rocket::request:{Form,FromForm};
使用rocket_contrib::json::json;
使用rocket_okapi::swagger_ui::*;
使用schemars::JsonSchema;
使用serde::{反序列化,序列化};
使用rocket::http::方法;
使用std::env;
使用std::process::命令;
使用火箭武器:{
允许出生,
Cors,CorsOptions,
};
#[派生(序列化、反序列化、JsonSchema)]
#[serde(重命名为_all=“camelCase”)]
结构用户{
用户id:u64,
用户名:String
}
//面向用户的impl{
//fn response_to(self,u:&Request)->response::Result Cors{
let allowed_origins=AllowedOrigins::some_确切(&[
"http://localhost:3000",
]);
公司{//5。
允许的来源,
expose_头:[“x-total-count”、“内容长度”、“服务器”]
.国际热核实验堆(iter)
.map(ToString::to_字符串)
.collect(),
允许的_方法:vec![Method::Get,Method::Post,Method::Patch].into_iter().map(From::From).collect(),
允许\u凭据:false,
…默认值::默认值()
}
.to_cors()
.expect(“构建CORS时出错”)
}
///#获取所有用户
#[openapi]
#[获取(“/user”)]
fn获取所有用户()->Json{
Json(vec![User{
用户id:88,
用户名:“goja288”。to_owned(),
}])
}
fn main(){
火箭:点火
.山(
"/",
使用openapi路由\u[
获取所有用户,
],
)
.山(
“/swagger ui/”,
使_-swagger _-ui(&SwaggerUIConfig){
url:“../openapi.json”。至_owned(),
…默认值::默认值()
}),
).attach(make_cors())
.launch();
}

尝试通过使用自定义结构包装
Json
(实现trait的)向响应添加标题(请参阅:

#[派生(调试)]
结构JsonWithTotalCount{
数据:Json,
总计数头:头响应程序{
让mut build=Response::build();
构建.合并(self.data.respond_to(request);
build.header(self.total\u count\u header);
build.ok()
}
}
并在您的
get_all_users
功能中使用它:

/// # Get all users
#[get("/user")]
fn get_all_users() -> JsonWithTotalCount<User> {
    JsonWithTotalCount::new(vec![User {
        user_id: 88,
        username: "goja288".to_owned(),
    }])
}
//#获取所有用户
#[获取(“/user”)]
fn获取所有用户()->JsonWithTotalCount{
JsonWithTotalCount::新建(vec![User{
用户id:88,
用户名:“goja288”。to_owned(),
}])
}

嗯,
X-Total-Count
标题是否存在于响应中?您可能需要手动添加它。如果标题不存在,CORS允许将不会有任何作用。感谢@OleksiiFilonenko的回答。事实上,我不太了解如何添加它。我尝试了各种方法。现在我正在阅读再次看看我是否可以实现它作为旁注,Rocket使得在任意响应中添加标题变得非常困难。这使它变得更容易。如果我删除openapi,使用该代码的惊人@Oleskii会起作用。谢谢!现在我需要弄清楚如何使用openapi(trait
OpenAPResponder)