Nuxt引入axios,并模块化请求

Nuxt直接引入axios,并模块化请求

一、npm安装

npm install axios

二、创建Axios扩展文件

/api/request.js 主要有以下内容

1、创建axios实例;

2、增加request拦截器,在请求发出前做自定义处理,比如加上token,sessionID

3、增加response拦截器,收到响应信息后判断响应状态,如果出错可以使用Message组件提示 - PS:在AsyncData方法中调用时,在服务器端执行,没有UI,所以无法进行UI展示提示.所以需要通过 context 的 process.server 变量判断当前环境是不是服务器

request.js 内容如下

/**  * 封装Axios  * 处理请求、响应错误信息  */
import { Message } from 'element-ui'
import axios from 'axios' //引用axios  
// create an axios instance 
const service = axios.create({
    baseURL: 'https://api.xxxxx.com',
    // 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['Content-Type'] = 'application/json'
    // 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 === 2000) {
      // 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.  
      return Promise.resolve(res)
      
    }
    else{
        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

三、创建API接口文件

创建API接口文件,抽出所有模块的异步请求 - 将同模块的请求写在一起,将ajax请求和页面隔离 - 如果后端API调整,只需要修改对应接口文件; /api/data.js

import request from './request'

// 获取优化方案留言
export function getPlaneFun(parmars) {
    return request({
        url: '/consult_api/guestBook/add',
        method: 'post',
        data: parmars
    })
}

四、组件中使用

1、第一中使用方式这种方式实现了SSR服务端渲染数据

这种方式中,async asyncData 中不能使用 this,所以这里如果想要动态的参数,可以通过 context 获取路由上边的参数,但是只能获取路由的参数;

import { getConst, getConstRead } from '~/api/data' 
export default {
    async asyncData(ctx) { 
        let pageNum = parseInt(ctx.route.params.page);
        let params = {
            pageSize: 10,
            pageNum: pageNum
        };
        return getConst(params)
        .then((data) => { 
            return { 
                inforList: data.body
            }
        })
    }      
}

2、第二种使用方式,此方法只引入axios就行

import axios from 'axios'
mounted(){
       this.getData();
},
methods: {
       async getData () {
            let { data } = await axios({
                withCredentials: true,
                method: 'post',
                url: 'http:xxxx',
                data: {
                    pageSize: this.pageSize
                }
            })
            this.inforList = data.body
       }
}

3、第三种继续使用封装模块,原理同第二种一样只是请求的时候使用 模块化请求;同样没有做到服务端渲染

猜你喜欢

转载自www.cnblogs.com/haonanZhang/p/12666078.html
今日推荐