Tauri2.0 稳定版插件http 在vue3中使用

HTTP插件使用

官网操作

  1. pnpm tauri add http
  2. src-tauri/capabilities/base.json中配置权限
   {
     "permissions": [
       {
         "identifier": "http:default",
         "allow": [{ "url": "https://*.tauri.app" }],
         "deny": [{ "url": "https://private.tauri.app" }]
         }
     ]
   } 
  1. 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"

需要注意的是 接口链接以.json结尾的需要再次调用一个方法

const jsonData = await response.json();

此时才算jsonData才是获取到的json数据

如果不是,需要调用 await response.text();(此处灵活使用,当前观点仅以我的测试来看)

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值