账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    如何在Nuxt的axios二次封装中使用store和服务端api
    22
    0

    项目中使用了token验证用户,我在NuxtServerInit中写入了将用户存储在Node的Session中的token写入到Store中,也就是说,用户登录后,有三个地方存储token,Node服务器中的Session、Store和本地localStorage,现在的问题是,当用户在其他地方登录,原token失效,刷新页面后,我需要在axios的响应拦截器中对这些数据进行处理,如果返回的code是10004,则清除本地、Store和Node服务器Session中存储的token,但问题是如何在axios中访问Node服务器中的session??下面是代码

    import axios from 'axios'
    import { handleRequestParams, handleWebStorage } from '@/utils/utils'
    import { WEBSTORAGE_TOKEN_NAME } from '@/config/config'
    import state from '@/store/state'
    import { apiByENV } from '@/config/config'
    
    const Axios = axios.create({
      baseURL: apiByENV,
      timeout: 5000,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      }
    })
    
    // http request请求拦截器(所有请求发送都要执行的操作)
    Axios.interceptors.request.use(
      config => {
        if (state.KGUser && state.KGUser.token) {
          config.headers.token = state.KGUser.token || ''
        }
        // 参数序列化
        if (config.method === 'post') {
          config.data = handleRequestParams(config.data, config.headers.token)
        }
    
        return config
      }, error => {
        return Promise.reject(error)
      }
    )
    
    // http response响应拦截器
    Axios.interceptors.response.use(
      response => {
    
    
        // 判断返回code是否为10004,token失效状态,若是则清除Node服务器session中的token及其本地localStrage中的token
        if (response.code === '10004') {
        }
        return response
      }, error => {
        return Promise.reject(error)
      }
    )
    
    export default Axios
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 队友最靓 普通会员 1楼

      在Nuxt.js中,我们经常需要从服务端获取数据,然后在页面中使用这些数据。这是一个常见的使用store和服务端API的场景。以下是如何在Nuxt.js中使用axios进行二次封装并使用store和服务端API的一般步骤:

      1. 在Nuxt.js项目中,首先需要安装axios库,可以通过npm或yarn进行安装。例如:

      npm install axios

      或者

      yarn add axios

      1. 创建一个axios.js文件,用于封装axios请求。在这个文件中,你可以定义axios的配置,包括请求头、请求方法、请求路径、请求体等。

      ```javascript import axios from 'axios';

      export default { // Axios配置 axios: { baseURL: 'http://localhost:3000/api', // 兼容baseURL headers: { 'Content-Type': 'application/json', }, timeout: 30000, // 请求超时时间 timeoutInterval: 3000, // 请求超时间隔时间 }, // 请求方法 methods: { fetchData() { return axios.get('/api/data') .then(response => { return response.data; }) .catch(error => { console.error(error); }); }, }, }; ```

      1. 在Nuxt.js的其他组件中,可以通过import语句导入axios.js文件,并在组件的methods中调用fetchData方法来使用axios的请求。

      ```javascript import axios from 'axios';

      export default { components: { // 其他组件 myComponent: { methods: { fetchData() { return axios.get('/api/data') .then(response => { return response.data; }) .catch(error => { console.error(error); }); }, }, }, }, }; ```

      这样,你就可以在Nuxt.js项目中使用axios库进行二次封装,并在组件中使用这些数据了。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部