2 个版本
0.1.1 | 2021 年 8 月 20 日 |
---|---|
0.1.0 | 2021 年 8 月 20 日 |
#512 在 WebAssembly
80 每月下载
14KB
188 代码行
WASM 请求
使用 rustwasm 保存样板代码创建 http 请求
如何使用
在 Cargo.toml
中包含
wasm_request = '0.1'
创建 http 请求
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Eur {
eur: f64,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct CurrentPrice {
current_price: Eur,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Price {
market_data: CurrentPrice,
}
async fn get_token_price() -> Price {
let options = get_options::<Price>(
"https://api.coingecko.com/api/v3/coins/1million-token",
Method::Get,
None,
None,
);
let price_1mt_token: Price = request(options).await.unwrap().into_serde().unwrap();
price_1mt_token
}
带有主体的 Post 请求
use wasm_request::{get_options, request, Method, DataType};
#[derive(Serialize, Deserialize, Debug)]
pub struct User {
pub email: String,
pub username: String,
pub password: String,
}
async fn create_user() {
let user = User {
email: "[email protected]".to_string(),
password: "test43214".to_string(),
}
let options = get_options::<User>(
"https://api.sport-example.com/login",
Method::Post,
None,
Some(DataType::Json(user)),
);
request(options).await.unwrap().into_serde().unwrap();
}
带有表单数据的 Post 请求
use wasm_request::{get_options, request, Method, DataType, get_defualt_headers};
use web_sys::FormData;
async fn add_form() {
let form = FormData::new().unwrap();
form.append_with_str("name", "Lee").unwrap();
form.append_with_str("email", "[email protected]").unwrap();
let headers = get_defualt_headers();
headers.delete("Content-Type").unwrap();
let options = get_options::<()>(
"https://api.sport-example.com/user",
Method::Post,
None,
Some(DataType::Form(form)),
);
request(options).await.unwrap().into_serde().unwrap();
}
管理本地存储
set_storage("food", "ramen");
let food = get_storage("food").unwrap();
delete_storage("food");
运行测试
wasm-pack test--无头--chrome--firefox
你喜欢 Wasm 请求吗
如果你喜欢 Yew Styles,请支持我的项目
- 使用 Brave 浏览器 可获得 BAT 奖励
- 使用此链接在 Binance(每次交易返10%手续费)创建账户
- Github Sponsors
Wasm 请求受 MIT 许可证
依赖关系
~7–10MB
~187K SLoC