接口请求
概述
在插件工程中,少不了需要请求接口获取数据,所以平台提供了请求能力包 @ones-op/fetch。在进行请求之前,你先要了解请求你请求的对象是什么?然后再选择合适的能力来使用。
为了让你快捷的调用 API 我们给你提供了 OPFetch
、Fetch
等方法,这样你就不需要在每个请求中编写如请求头之类的重复信息,简化了你的开发工作量。
使用
前端请求
下面将以 OPFetch
为例,教你如何给插件后端发送请求。
信息
我们推荐
- OPFetch 与 ONES 相关 API
- Fetch 其他 API
第一步:安装依赖
进入插件工程的 /web
目录,执行以下命令进行依赖安装:
- npm
- Yarn
- pnpm
npm install @ones-op/fetch
yarn add @ones-op/fetch
pnpm add @ones-op/fetch
第二步:请求
使用 ONES CLI 创建插件工程的时候,默认帮你往 ONES 注册了一个 API:hello。
往 plugin.yaml
中新增了一段配置:
config/plugin.yaml
apis:
- type: addition
methods:
- POST
url: /hello
function: hello
往 index.ts
中注入了 API 的实现:
/backend/src/index.ts
// example function
export async function hello(request: PluginRequest): Promise<PluginResponse> {
const body = request.body || {}
Logger.info('[Plugin] hello ======= 请求成功')
return {
body: {
res: 'hello world',
requestBody: body,
},
}
}
接下来我们就是用 OPFetch
来 请求这个接口。
import { Button } from '@ones-design/core'
import { OPFetch } from '@ones-op/fetch'
import React from 'react'
export const App = () => {
const handleFetchHello = () => {
const response = OPFetch({
url: '/project/api/project/hello',
method: 'POST',
})
}
return (
<div>
<Button onClick={handleFetchHello}>Fetch hello</Button>
</div>
)
}
具体 API 使用方法及参数解析请参照:@ones-op/fetch。
后端请求
下面将以 OPFetch
为例,教你如何给 ONES 发送请求。