NuxtJS如何利用axios異步請求


第一種:使用nuxt 提供的 Axios插件 @nuxtjs/axios

1、安裝:npm install @nuxtjs/axios -d

2、配置 nuxt.config.js

exports default { modules: [ '@nuxtjs/axios', ] }

3、在提供的context(上下文對象)中取得$axios

async asyncData({ $axios }) { const ip = await $axios.$get('...') return { ip } }

4、使用Nuxt plugin擴展Axios

  nuxt會在vue.js程序啟動前調用 plugins目錄下的腳本,並且以context(上下文對象)作為參數,可以取到$axios

  創建 plugins/axios.js 並定義axios的攔截器,定義請求的各個階段需要進行的處理

export default function({ $axios, redirect }) { // request interceptor
 $axios.interceptors.request.use( config => { // do something before request is sent
      return config }, error => { // do something with request error
      return Promise.reject(error) } ) $axios.onRequest(config => { console.log('Making request to ' + config.url) }) // response interceptor
 $axios.interceptors.response.use( /** * Determine the request status by custom code * Here is just an example * You can also judge the status by HTTP Status Code */ response => { const res = response.data if (res.code === 20000) { return res } else { redirect('/404') // if the custom code is not 200, it is judged as an error.
 } return Promise.reject(new Error(res.msg || 'Error')) }, error => { console.log('err' + error) // for debug

      return Promise.reject(error) } ) $axios.onError(error => { const code = parseInt(error.response && error.response.status) if (code === 400) { redirect('/404') } else if (code === 500) { redirect('/500') } }) }

5、添加插件到nuxt.config.js配置文件

plugins: [ '@/plugins/axios' ],

第二種:直接引入axios,並模塊化請求,就像vue中那樣使用

1、安裝:npm install axios --save

2、創建Axios擴展request.js

  在/api/request.js主要做了3件事:

  • 創建axios實例
  • 增加request攔截器,在請求發出前做自定義處理,比如加上token,sessionID
  • 增加response攔截器,收到響應信息后判斷響應狀態,如果出錯可以使用Message組件提示

  PS:在AsyncData方法中調用時,在服務器端執行,沒有UI,所以無法進行UI展示提示。所以需要通過process.server變量判斷當前環境是不是服務器。

/** * 封裝Axios * 處理請求、響應錯誤信息 */ import { Message } from 'element-ui'  //引用餓了么UI消息組件
import axios from 'axios' //引用axios // create an axios instance
const service = axios.create({ baseURL: '/api/', // 所有異步請求都加上/api,nginx轉發到后端Springboot
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
}) // request interceptor
service.interceptors.request.use( config => { // do something before request is sent // config.headers['-Token'] = getToken()
    return config }, error => { // do something with request error
    console.log(error) // for debug
    return Promise.reject(error) } ) // response interceptor
service.interceptors.response.use( /** * If you want to get http information such as headers or status * Please return response => response */

  /** * Determine the request status by custom code * Here is just an example * You can also judge the status by HTTP Status Code */ response => { const res = response.data //res is my own data

    if (res.code === 20000) { // do somethings when response success // Message({ // message: res.message || '操作成功', // type: 'success', // duration: 1 * 1000 // })
      return res } else { // if the custom code is not 200000, it is judged as an error.
 Message({ message: res.msg || 'Error', type: 'error', duration: 2 * 1000 }) return Promise.reject(new Error(res.msg || 'Error')) } }, error => { console.log('err' + error) // for debug
 Message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error) } ) export default service //導出封裝后的axios

3、創建API接口文件

  創建API接口文件,抽出所有模塊的異步請求,將同模塊的請求寫在一起,將ajax請求和頁面隔離,如果后端API調整,只需要修改對應接口文件

import request from './request'

/** * 獲取博客詳情 * @param id 博客ID */ export function getBlog(id) { return request({ url: 'blog/detail/' + id, method: 'get' }) } /** * 獲取博客列表 * @param page 頁碼 * @param max 每頁顯示數量 */ export function getList(page, max) { return request({ url: 'blog/list', method: 'get', params: { page, max } }) }

4、vue組件使用

import { getBlog} from '~/api/blog' asyncData({ params, redirect}) { return getBlog(params.id) //直接使用API導出的方法進行請求
      .then(({ data }) => { return { blog: data } }).catch((e) => {  //從nuxt context 中獲取 redirect 進行跳轉
        redirect('/404') }) }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM