reqwest crate GET方法报错RelativeUrlWithoutBase的解决办法
测试请求失败:RelativeUrlWithoutBase 错误排查
问题背景
跟随《Zero to Production》书籍学习时,此前正常运行的健康检查测试,执行cargo test时抛出RelativeUrlWithoutBase错误。
相关代码
TestApp 定义与 spawn_app 函数
pub struct TestApp { pub address: String, pub pool: PgPool, } async fn spawn_app() -> TestApp { let listener = TcpListener::bind("127.0.0.1:0").expect("failed to bind to the port"); let port = listener.local_addr().unwrap().port(); let address = format!("127.0.0.1:{}", port); let configuration = get_configuration().expect("failed to read configuration"); let connection_pool = PgPool::connect(&configuration.database.connection_string()).await.expect("failed to connect to postgres"); let server = run(listener, connection_pool.clone()).expect("failed to bind to address"); let _ = tokio::spawn(server); TestApp{ address, pool: connection_pool, } }
测试函数
#[tokio::test] async fn health_check_works() { let app = spawn_app().await; let client = reqwest::Client::new(); let response = client .get(&format!("{}/health_check",&app.address)) .send() .await .expect("Failed to execute request."); assert!(response.status().is_success()); assert_eq!(Some(0), response.content_length()); }
错误信息
thread 'health_check_works' panicked at 'Failed to execute request.: reqwest::Error { kind: Builder, source: RelativeUrlWithoutBase }', tests/health_check.rs:36:10
原因
reqwest 的 get 方法要求传入完整的绝对URL(必须包含协议前缀,如http://)。当前代码生成的address仅为127.0.0.1:xxxx格式,缺少协议前缀,导致reqwest无法识别为合法的基础URL,进而判定为相对路径,抛出该错误。
解决步骤
修改spawn_app函数中生成address的代码,添加http://前缀:
// 原代码 // let address = format!("127.0.0.1:{}", port); // 修改后 let address = format!("http://127.0.0.1:{}", port);
修改后,测试函数拼接出的URL为http://127.0.0.1:xxxx/health_check,属于完整的绝对URL,reqwest可正常解析并发送请求。
内容的提问来源于stack exchange,提问作者Sarang Dutta
相关产品推荐
相关产品推荐

