Nuxt处理服务端请求拦截方法

Nuxt处理服务端请求拦截方法:

  1. Vue页面apiPost方法入参请求
  2. server/utils/http/api/all发出请求
  3. 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)
})

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注