Nuxt3 data request and packaging


foreword

This article records the method of Nuxt3 network request, and combines the needs of its own project to uniformly encapsulate the data requests in it, so that the common request logic can be processed uniformly, using the useFetch method that comes with Nuxt3.


1. Data request method in Nuxt3

Nuxt3 provides a variety of methods to handle data fetching in your application:

  • $fetch
  • useFetch
  • useLazyFetch
  • you are in AsyncData
  • you are in LazyAsyncData

Two, unjs/ofetch library

Nuxt3 does not recommend and does not need to use Axios for network requests. Axios was originally a package for XMLHttpRequest, but now the function of network requests is gradually replaced by Fetch API from XMLHttpRequest. Browsers already support native support for fetch, and Node v17.5 also introduced it Added native support for fetch. The official team of Nuxt3 further encapsulates fetch, the encapsulated project is called ofetch , and integrates it into Nuxt3, which is $fetchthe method mentioned at the beginning.

3. The difference between request methods

1. you are in AsyncData

It is necessary to provide a processing function for cache deduplication key and data request.
The first parameter is the key, but even if you don't pass the key, Nuxt will generate one for you based on the file name and line number.

const {
    
     data, pending, error, refresh } = await useAsyncData(
  'mountains',
  () => $fetch('https://api.nuxtjs.dev/mountains')
)

2. useFetch

useFetchThis composable function provides a convenience wrapper for useAsyncData and $fetch. It automatically generates keys based on URL and fetch options, provides type hints for request URLs based on server routes, and infers API response types.
Multiple calls to useFetch are recommended <script setup>as it removes the limitation of using top-level waits.

useFetch is a layer of packaging for useAsyncData, which can be understood as all the useAsyncData methods that choose the default configuration, useFetch(url) is almost equivalent to useAsyncData(url, () => $fetch(url)) - it is the most common use case Syntactic sugar for developers.

const param1 = ref('value1')
const {
    
     data, pending, error, refresh } = await useFetch('https://api.nuxtjs.dev/mountains',{
    
    
    query: {
    
     param1, param2: 'value2' }
})

3. useLazyAsyncData and useLazyFetch

These two APIs correspond to useAsyncData and useFetch respectively, and they are used in the same way. Just set Lazy in the configuration option to true, that is, using useLazyFetch and useLazyAsyncData will not block the navigation jump when rendering on the client side, which means you need to process data If it is null, set a default value for data; while the rendering effect on the server side is the same, it will still block page rendering.

Four, package useFetch

Since useFetchit is already a simplified request method after encapsulation, further encapsulation is performed based on the useFetch method, mainly adding the global baseURL, and adding request and response interception. Here it is good to package according to the actual project requirements.

Before encapsulation, there are a few tips for using Nuxt3:

1. Nuxt3 usage skills

①: Composables directory is automatically imported

Nuxt 3 uses the composables/ directory to automatically import Vue compos into the app using auto-imports!

By default, Nuxt3 will automatically import the first-level files in this directory, so the functions that encapsulate network requests can be written in this directory and exported to be used freely in the project.

②: Define Runtime Config public variables

useRuntimeConfig is used to expose configuration variables in the application.

Define public variables for use on the client side:

export default defineNuxtConfig({
    
    
  runtimeConfig: {
    
    
    // apiSecret 只能在服务器端上访问
    apiSecret: '123',
    // public 命名空间中定义的,在服务器端和客户端都可以普遍访问
    public: {
    
    
      apiBase: process.env.NUXT_PUBLIC_API_BASE
    }
  }
})

How to use:

  const config = useRuntimeConfig();
  const baseURL = config.public.apiBase;

③: Define the env environment variable

In production runtime, you should use platform environment variables, .env is not used.

You can’t get the content in .env by directly using process.env to access environment variables on the client side, but only in the node environment on the server side, so you must cooperate with useRuntimeConfig to use the configuration in .env.

NUXT_Runtime configuration values ​​can be updated with matching environment variable names prefixed with .

//.env.development
NUXT_PUBLIC_API_BASE = 'https://api-test.com'
//.env.production
NUXT_PUBLIC_API_BASE = 'https://api.com'

The following formally enters the link of encapsulating data request functions.

2. Encapsulation function

// composables/getData.ts
import type {
    
     LocationQuery } from 'vue-router';
import type {
    
     NitroFetchRequest } from 'nitropack';
import type {
    
     FetchOptions } from 'ofetch';
import {
    
     showToast } from 'vant';
import fs from 'fs';

export function getFetchData(url: NitroFetchRequest, opts: FetchOptions<any>, method: 'get' | 'post' | 'GET' | 'POST' = 'get') {
    
    
  // 接口传参要求
  interface QueryItem {
    
    
    uid?: string;
    token?: LocationQuery;
  }
  const route = useRoute();
  const query: QueryItem = route.query;

  const config = useRuntimeConfig();
  return useFetch(url, {
    
    
  	// method此处仅仅只处理了get与post请求
    method,
    // ofetch库会自动识别请求地址,对于url已包含域名的请求不会再拼接baseURL
    baseURL: config.public.baseURL + '/xxx',
    // onRequest相当于请求拦截
    onRequest({
     
      request, options }) {
    
    
      // 设置请求头
      options.headers = {
    
     ...options.headers, authorization: 'xxx' };
      // 设置请求参数
      if (method === 'POST' || method === 'post') {
    
    
        options.body = {
    
     ...opts };
        options.query = query;
      } else {
    
    
        options.query = Object.assign(query, {
    
     ...opts });
      }
    },
    // onResponse相当于响应拦截
    onResponse({
     
      response }) {
    
    
      // 处理响应数据
      if (response._data.error) {
    
    
        console.warn('=== error url: ', url, '\n params:', opts, '\n response:', response._data);
        // 采用vant组件弹出报错弹窗
        showToast(response._data.message);
		// 处理服务端渲染时接口报错,可接入日志系统或者邮件系统,此处测试demo采取写入文件系统
        fs.writeFileSync('error.txt', `error url:${
      
      url}\n response:${
      
      response._data.message}\n`, {
    
     flag: 'a' });
      } else {
    
    
        response._data = response._data.data;
      }
    },
    onRequestError({
     
      request, options, error }) {
    
    
      // 处理请求错误
      console.warn('request error', error);
      showToast('Request Error');
    },
    onResponseError({
     
      request, response, options }) {
    
    
      // 处理响应错误
      console.warn('request error', response);
      showToast('Request Error');
    },
  });
}

3. call

Directly use getFetchDatamethods in the project to handle asynchronous requests

// get请求
const {
    
     data, refresh } = await getFetchData('xxx/getList', {
    
     id: 1 });

// post请求
const {
    
     data, refresh } = await getFetchData(
	'xxx/getList',
	{
    
    
	  memberLevel: 1,
	  pageNum: 1,
	  pageSize: 10,
  	},
  	'post'
);

Summarize

The above is all the content. This article briefly introduces the data acquisition method of Nuxt3. For detailed usage methods and usage skills, you need to refer to official documents and excellent projects in the community. Regarding the encapsulation of data requests, I have written a blog about Axios encapsulation before. Interested students can refer to ( axios encapsulation—vue3 project ). The encapsulation of Nuxt3 this time is only a basic display, and it needs to be used flexibly according to its own business needs. In addition, I have just learned Nuxt3, if there is anything wrong, please correct me.
If this article is helpful to you, you are welcome to [Like] and [Favorite]! You are also welcome to [comments] to leave valuable comments, discuss and learn together~

Guess you like

Origin blog.csdn.net/m0_55119483/article/details/131709037