主题
接口请求
在 uniapp
项目中,我们规定了接口的统一目录api
目录。再上一节的目录结构中有所说明。
GET 请求
ts
import { http } from '@/utils/http'
return http({
url: `/someurl`,
method: 'GET',
query: { name: 'value' }
})
POST 请求
ts
import { http } from '@/utils/http'
return http({
url: `/someurl`,
method: 'POST',
data: { account, password, type: 'password' }
})
文件上传
ts
import { uniFileUpload } from '@/utils/http'
return uniFileUpload({
url: `/someurl`,
method: 'POST',
filePath: filePath, // 文件地址
name: 'avatar', // 文件名称,这里叫 avatar
formData: {
// form 表单数据
...params,
type
}
})
如何使用
找到 api/login.ts
,首先查看下面的代码。创建一个使用账户密码登录 login
方法。
ts
export const login = (account: string, password: string) => {
return http({
url: `/login`,
method: 'POST',
data: { account, password, type: 'password' }
})
}
在页面引入
ts
// 首先引入 login 方法
import { login } from '@/api/login'
login('account', 'password').then((r) => {
// 处理返回的响应
})