今天给大家分享一下nuxt3的useFetch在服务端如何请求接口,我这里使用的是ts,同理使用js的小伙伴可以根据实际情况进行调整,本篇博客仅供参考哦~
目录
具体实现
在utils目录下新建一个client.ts文件,这个文件是封装useFetch请求接口用的,代码如下:
import { doError } from './apiError'
// 这里是规定后端返回的数据格式规范
export interface ResOptions<T> {
data?: T
code?: number
msg?: string
}
const fetch = (url: string, options?: any): Promise<any> => {
const config = useRuntimeConfig()
// 获取配置域名
let baseUrl = config.public.apiUrlInternal
// 拼接请求地址
const reqUrl = baseUrl + url
return new Promise((resolve, reject) => {
useFetch(reqUrl, { ...options }).then(({ data, error }: any) => {
const value: ResOptions<any> = data.value
resolve(value)
// 判断是否有错误产生
if (error.value) {
doError(error.value?.statusCode, reqUrl)
reject(error.value)
}else{
resolve(ref(value).value)
}
}).catch((err: any) => {
// 接口请求异常的操作写在这里
console.log(err)
reject(err)
})
})
}
export default new class Http {
get(url: string, params?: any): Promise<any> {
return fetch(url, { method: 'get', params })
}
post(url: string, params?: any): Promise<any> {
return fetch(url, { method: 'post', params })
}
put(url: string, body?: any): Promise<any> {
return fetch(url, { method: 'put', body })
}
delete(url: string, body?: any): Promise<any> {
return fetch(url, { method: 'delete', body })
}
}
在utils目录下新建一个apiError.ts文件,这个文件用来封装错误code码,具体内容如下:
export const doError = (error: number, reqUrl: string) => {
// 这里规定一些异常码所代表的意义
if (error === 404) {
setError(401,reqUrl,'数据不存在')
} else if (error === 403) {
setError(403,reqUrl,'无权限访问')
} else if (error >= 500) {
setError(error,reqUrl,'服务器内部错误')
} else if (error === 0) {
setError(0,reqUrl,'网络错误')
}
}
const setError = (error: number, statusMessage: string, message: string) => {
throw createError({
statusCode: error,
statusMessage,
message,
})
}
封装接口请求方法
import Http from '~~/utils/client'
/**
* 根据标签code获取标签名字
* @param code 标签code
* @returns
*/
export const getLabelNameByCode = async (code: string):Promise<string> => {
return await Http.get('api-app/tag/getByCode', {code: code})
}
补充
nuxt3里配置环境变量的方法:
在.env文件里配置
# 服务端API请求地址
NUXT_PUBLIC_API_URL_INTERNAL=http://xxxx.xxxx.com
# 客户端API请求域名,用户浏览器端发起请求(这里不要加http前缀,因为要同时适配http/https)
NUXT_PUBLIC_API_URL_PUBLIC=//xxxx.xxxx.com
然后在nuxt.config.ts里,把对应名字加上(这里注意命名要和你在env文件里命名对应上,比如说“NUXT_PUBLIC_API_URL_PUBLIC =》 apiUrlPublic”)
然后具体获取环境变量如下:
const config = useRuntimeConfig()
const baseUrl = config.public.apiUrlInternal
小结
希望这篇文章可以帮助到大家!