HTTP插件使用
官网操作
pnpm tauri add http
src-tauri/capabilities/base.json
中配置权限
{
"permissions": [
{
"identifier": "http:default",
"allow": [{ "url": "https://*.tauri.app" }],
"deny": [{ "url": "https://private.tauri.app" }]
}
]
}
- ts文件使用
import { fetch } from '@tauri-apps/plugin-http';
// Send a GET request
const response = await fetch('http://my.api.host/data.json', {
method: 'GET',
});
console.log(response.status); // e.g. 200
console.log(response.statusText); // e.g. "OK"
若按照如上操作,会出现以下报错
事实上,2.0版本tauri会自动生成个权限文件
src-tarui/capabilities/default.json
并且文件内容里也有默认权限
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": [
"main"
],
"permissions": [
"core:default",
"shell:allow-open",
"http:default"
]
}
我们只需要在permissions
中把官网第二步配置权限内容加进去就行了
完整代码
权限部分
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": [
"main"
],
"permissions": [
"core:default",
"shell:allow-open",
{
"identifier": "http:default",
"allow": [{
"url": "https://*.tauri.app"
}],
"deny": [{
"url": "https://private.tauri.app"
}]
}
]
}
Javascript
import { fetch } from '@tauri-apps/plugin-http';
const toNews = async () => {
const response = await fetch('https://*.tauri.app', {
method: 'GET',
});
console.log(response)
};
注意
在官网 tauri2.0 http插件使用实例中,网址:
https://v2.tauri.app/reference/javascript/http/
const response = await fetch("http://my.json.host/data.json");
console.log(response.status); // e.g. 200
console.log(response.statusText); // e.g. "OK"