Nuxt处理服务端请求拦截方法:
- Vue页面
apiPost
方法入参请求 server/utils/http
对/api/all
发出请求server/api/all
对服务器发出请求
server/api/all.ts
// server/api/all.ts
export default defineEventHandler(async (event) => {
const { method } = event;
if (method === "GET") {
// 'GET'
}
if (method === "POST") {
const body = await readBody(event);
const { api, params, headers } = body;
let res;
const data = await $fetch(api, {
method,
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify(params)
}
).catch((error) => {
if (error) {
return error;
}
});
if (data) {
res = data;
return res;
}
}
});
server/utils/http.ts
// server/utils/http.ts
export const apiPost = async (api:string, params:object, headers:object) => {
const {data:data,error:error} = await useFetch('/api/all',{
method: 'post',
body: {
headers:headers,
api:api,
params: params
}
})
if(data.value){
return data
}
if(error.value){
return error
}
}
Vue页面代码
import { apiPost } from '~/server/utils/http'
apiPost('api',{}, {}).then(res=>{
console.log('res',res)
}).catch(err=>{
console.log('err',err)
})