Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 如何从另一个文件调用函数并在web中获取_Json_Rust_Rust Actix_Rs - Fatal编程技术网

Json 如何从另一个文件调用函数并在web中获取

Json 如何从另一个文件调用函数并在web中获取,json,rust,rust-actix,rs,Json,Rust,Rust Actix,Rs,我对生锈还不熟悉,但我仍在学习。在main.rs和routes.rs上有锈蚀应用。main.rs文件具有服务器配置,routes.rs具有具有路径的方法 梅因 #[macro_use] extern crate log; use actix_web::{App, HttpServer}; use dotenv::dotenv; use listenfd::ListenFd; use std::env; mod search; #[actix_rt::main] async fn main(

我对生锈还不熟悉,但我仍在学习。在main.rs和routes.rs上有锈蚀应用。main.rs文件具有服务器配置,routes.rs具有具有路径的方法

梅因

#[macro_use]
extern crate log;

use actix_web::{App, HttpServer};
use dotenv::dotenv;
use listenfd::ListenFd;
use std::env;

mod search;

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

    let mut listenfd = ListenFd::from_env();
    let mut server = HttpServer::new(|| 
        App::new()
            .configure(search::init_routes)
    );

    server = match listenfd.take_tcp_listener(0)? {
        Some(listener) => server.listen(listener)?,
        None => {
            let host = env::var("HOST").expect("Host not set");
            let port = env::var("PORT").expect("Port not set");
            server.bind(format!("{}:{}", host, port))?
        }
    };

    info!("Starting server");
    server.run().await
}
现在我想要的是使用另一个单独的rs文件(fetch_test.rs)中的方法获取API,并将其路由到routes.rs文件中。然后,我希望通过运行该路由路径(链接)从web浏览器获得响应

我怎么能做这些事??我到处找,但没找到有用的东西。有时我也不理解一些文档

**更新

获取测试资源

extern crate reqwest;
use hyper::header::{Headers, Authorization, Basic, ContentType};

pub fn authenticate() -> String {

fn construct_headers() -> Headers {
    let mut headers = Headers::new();
    headers.set(
        Authorization(
            Basic {
                username: "HI:ABGTYH".to_owned(),
                password: Some("%8YHT".to_owned())
            }
        )
     );
    headers.set(ContentType::form_url_encoded());
    headers
}

let client = reqwest::Client::new();
let resz = client.post("https://api.test.com/auth/token")
    .headers(construct_headers())
    .body("grant_type=client_credentials")
    .json(&map)
    .send()
    .await?;

}
错误


   Compiling sabre-actix-kist v0.1.0 (E:\wamp64\www\BukFlightsNewLevel\flights\APIs\sabre-actix-kist)
error[E0425]: cannot find value `map` in this scope
  --> src\search\routes\common.rs:28:12
   |
28 |     .json(&map)
   |            ^^^ not found in this scope

error[E0728]: `await` is only allowed inside `async` functions and blocks
  --> src\search\routes\common.rs:25:12
   |
4  |   pub fn authenticate() -> String {
   |          ------------ this is not `async`
...
25 |   let resz = client.post("https://api-crt.cert.havail.sabre.com/v2/auth/token")
   |  ____________^
26 | |     .headers(construct_headers())
27 | |     .body("grant_type=client_credentials")
28 | |     .json(&map)
29 | |     .send()
30 | |     .await?;
   | |__________^ only allowed inside `async` functions and blocks

error[E0277]: the trait bound `std::result::Result<search::routes::reqwest::Response, search::routes::reqwest::Error>: std::future::Future` is not satisfied
  --> src\search\routes\common.rs:25:12
   |
25 |   let resz = client.post("https://api-crt.cert.havail.sabre.com/v2/auth/token")
   |  ____________^
26 | |     .headers(construct_headers())
27 | |     .body("grant_type=client_credentials")
28 | |     .json(&map)
29 | |     .send()
30 | |     .await?;
   | |__________^ the trait `std::future::Future` is not implemented for `std::result::Result<search::routes::reqwest::Response, search::routes::reqwest::Error>`

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
  --> src\search\routes\common.rs:25:12
   |
4  |  / pub fn authenticate() -> String {
5  |  |
6  |  |     let res = reqwest::get("http://api.github.com/users")
7  |  | .expect("Couldnt")
...   |
25 |  | let resz = client.post("https://api-crt.cert.havail.sabre.com/v2/auth/token")
   |  |____________^
26 | ||     .headers(construct_headers())
27 | ||     .body("grant_type=client_credentials")
28 | ||     .json(&map)
29 | ||     .send()
30 | ||     .await?;
   | ||___________^ cannot use the `?` operator in a function that returns `std::string::String`
31 |  |
32 |  | }
   |  |_- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `std::ops::Try` is not implemented for `std::string::String`
   = note: required by `std::ops::Try::from_error`

error[E0308]: mismatched types
 --> src\search\routes\common.rs:4:26
  |
4 | pub fn authenticate() -> String {
  |        ------------      ^^^^^^ expected struct `std::string::String`, found `()`
  |        |
  |        implicitly returns `()` as its body has no tail or `return` expression

编译sabre actix kist v0.1.0(E:\wamp64\www\BukFlightsNewLevel\flights\API\sabre actix kist)
错误[E0425]:在此范围内找不到值'map'
-->src\search\routes\common.rs:28:12
|
28 |.json(&map)
|^^^^在此范围内找不到
错误[E0728]:'await'仅允许在'async'函数和块中使用
-->src\search\routes\common.rs:25:12
|
4 | pub fn authenticate()->字符串{
|-----这不是“异步”`
...
25 |让resz=client.post(“https://api-crt.cert.havail.sabre.com/v2/auth/token")
|  ____________^
26 | |头(构造|头())
27 | |主体(“授予类型=客户凭证”)
28 | |.json(&map)
29 | |发送()
30.等待?;
|| ______ ^仅允许在'async'函数和块中使用
错误[E0277]:未满足特性绑定'std::result::result:std::future::future'
-->src\search\routes\common.rs:25:12
|
25 |让resz=client.post(“https://api-crt.cert.havail.sabre.com/v2/auth/token")
|  ____________^
26 | |头(构造|头())
27 | |主体(“授予类型=客户凭证”)
28 | |.json(&map)
29 | |发送()
30.等待?;
|| u______________________`
错误[E0277]:“?”运算符只能用于返回“Result”或“Option”的函数(或实现“std::ops::Try”的其他类型)
-->src\search\routes\common.rs:25:12
|
4 |/pub fn authenticate()->字符串{
5  |  |
6 | |让res=reqwest::get(“http://api.github.com/users")
7 | |期望(“不能”)
...   |
25 | |让resz=client.post(“https://api-crt.cert.havail.sabre.com/v2/auth/token")
|  |____________^
26 | | |.头文件(构造_头文件())
27 | | |主体(“授予类型=客户凭证”)
28 | | |.json(&map)
29 | | |发送()
30 | | |等待?;
|在返回'std::string::string'的函数中,不能使用`?`运算符`
31 |  |
32 |  | }
||-此函数应返回'Result'或'Option'以接受'`
|
=帮助:“std::ops::Try”特性没有为“std::string::string”实现`
=注意:`std::ops::Try::from_error'所需`
错误[E0308]:类型不匹配
-->src\search\routes\common.rs:4:26
|
4 | pub fn authenticate()->字符串{
|--------------应为结构“std::string::string”,找到“()`
|        |
|隐式返回“()”,因为它的主体没有尾部或“return”表达式
**再次更新

extern crate reqwest;
use hyper::header::{Headers, Authorization, Basic, ContentType};

fn construct_headers() -> Headers {
    let mut headers = Headers::new();
    headers.set(
        Authorization(
            Basic {
                username: "HI:ABGTYH".to_owned(),
                password: Some("%8YHT".to_owned())
            }
        )
     );
    headers.set(ContentType::form_url_encoded());
    headers
}

pub async fn authenticate() -> Result<String, reqwest::Error> {

let client = reqwest::Client::new();
let resz = client.post("https://api.test.com/auth/token")
    .headers(construct_headers())
    .body("grant_type=client_credentials")
    .json(&map)
    .send()
    .await?;

}
外部板条箱要求;
使用hyper::header::{Headers,Authorization,Basic,ContentType};
fn构造_头()->头{
让mut headers=headers::new();
headers.set(
授权书(
基本的{
用户名:“HI:ABGTYH”。to_owned(),
密码:一些(“%8YHT”。to_owned())
}
)
);
set(ContentType::form_url_encoded());
标题
}
发布异步fn authenticate()->结果{
让client=reqwest::client::new();
让resz=client.post(“https://api.test.com/auth/token")
.headers(构造_headers())
.body(“授权类型=客户凭据”)
.json(&map)
.send()
.等待?;
}
**新错误

error[E0425]: cannot find value `map` in this scope
  --> src\search\routes\common.rs:24:12
   |
24 |     .json(&map)
   |            ^^^ not found in this scope

error[E0277]: the trait bound `impl std::future::Future: search::routes::serde::Serialize` is not satisfied
  --> src\search\routes.rs:24:29
   |
24 |     HttpResponse::Ok().json(set_token)
   |                             ^^^^^^^^^ the trait `search::routes::serde::Serialize` is not implemented for `impl std::future::Future`

error[E0308]: mismatched types
  --> src\search\routes\common.rs:22:14
   |
22 |     .headers(construct_headers())
   |              ^^^^^^^^^^^^^^^^^^^ expected struct `search::routes::reqwest::header::HeaderMap`, found struct `hyper::header::Headers`
   |
   = note: expected struct `search::routes::reqwest::header::HeaderMap`
              found struct `hyper::header::Headers`

error[E0599]: no method named `json` found for struct `search::routes::reqwest::RequestBuilder` in the current scope
  --> src\search\routes\common.rs:24:6
   |
24 |     .json(&map)
   |      ^^^^ method not found in `search::routes::reqwest::RequestBuilder`

error[E0308]: mismatched types
  --> src\search\routes\common.rs:18:63
   |
18 |   pub async fn authenticate() -> Result<String, reqwest::Error> {
   |  _______________________________________________________________^
19 | |
20 | | let client = reqwest::Client::new();
21 | | let resz = client.post("https://api.test.com/auth/token")
...  |
27 | |
28 | | }
   | |_^ expected enum `std::result::Result`, found `()`
   |
   = note:   expected enum `std::result::Result<std::string::String, search::routes::reqwest::Error>`
           found unit type `()`
错误[E0425]:在此范围内找不到值'map'
-->src\search\routes\common.rs:24:12
|
24 |.json(&map)
|^^^^在此范围内找不到
错误[E0277]:未满足特性绑定'impl std::future::future:search::routes::serde::Serialize'
-->src\search\routes.rs:24:29
|
24 | HttpResponse::Ok().json(设置令牌)
|^^^^^^^^未为'impl std::future::future'实现特征'search::routes::serde::Serialize'`
错误[E0308]:类型不匹配
-->src\search\routes\common.rs:22:14
|
22 |.头(构造|头())
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^`
|
=注意:应为结构'search::routes::reqwest::header::HeaderMap'`
找到结构“hyper::header::Headers”`
错误[E0599]:在当前作用域中找不到struct`search::routes::reqwest::RequestBuilder`的名为`json`的方法
-->src\search\routes\common.rs:24:6
|
24 |.json(&map)
|在'search::routes::reqwest::RequestBuilder'中找不到^`
错误[E0308]:类型不匹配
-->src\search\routes\common.rs:18:63
|
18 |发布异步fn authenticate()->结果{
|  _______________________________________________________________^
19 | |
20 | |让client=reqwest::client::new();
21 | |让resz=client.post(“https://api.test.com/auth/token")
...  |
27 | |
28 | | }
|| ^应为枚举'std::result::result',找到了'()`
|
=注意:预期枚举`std::result::result`
找到的单位类型为“”()`

我可以澄清您的问题吗?据我所知,您已经知道如何使用另一个文件中的函数。您需要知道如何发出API请求并将结果表单作为响应传递给请求吗

首先,您需要使用例如
reqwest
lib创建
fetch\u test.rs

let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
    .json(&map)
    .send()
    .await?;
  • 映射结果或按原样传递

  • 在routes.rs中返回结果:
    HttpResponse::Ok().json(res)
    
    let client = reqwest::Client::new();
    let res = client.post("http://httpbin.org/post")
        .json(&map)
        .send()
        .await?;