RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题

问题[axios]

Martin Hope
Sun-ny11
Asked: 2024-11-02 19:31:24 +0000 UTC

当Axios拦截器重复请求时,如何将数据上传到MobX存储?

  • 5

当accessToken它变坏时,interceptor它会捕获错误,更新令牌并重复请求。重复请求,但没有数据写入store。如何实施?

  (response: AxiosResponse) => {
    return response
  },
  async (error: unknown) => {
    if (isAxiosError(error)) {
      if (error.response?.status === StatusCode.Unauthorized) {
        if (error.config?.url === Endpoints.updateToken) {
          return Promise.reject(error)
        } else {
          try {
            const params = error.config || undefined

            await authStore.updateToken(params)
          } catch (updateError) {
            return Promise.reject(updateError)
          }
        }
      }
    }

    return Promise.reject(error)
  }
)


  async updateToken(
    params: InternalAxiosRequestConfig | undefined
  ) {
    try {
      const newToken = await authApi.updateToken()

      setToLocalStorage(StorageKeys.AccessToken, newToken)

      if (params) {
        params.headers.Authorization = `Bearer ${newToken}`

        const repeatedRequest = await instance.request(params)

        // ???

      }
    } catch (error) {
      return Promise.reject(error)
    }
  }

我尝试重复的不是请求,而是操作,从 axios error.config 获取数据,但带有路径参数的请求让我困惑"/api/v1/posts/{postId}/comments/{commentId}/answers/{answerId}/likes"

axios
  • 1 个回答
  • 22 Views
Martin Hope
Spartak Borisov
Asked: 2022-07-22 18:49:35 +0000 UTC

在站点上实施授权时出错:错误 POST 404 (OK)

  • 0

无法弄清楚如何解决 POST 请求问题。我正在尝试在站点上实现授权(通过 Vuejs、vuex、vue-router、axios)。如果你能给我一些建议,我会很高兴的。我搜索了论坛的信息,但其他地方描述的情况不适合我的情况。为什么是 404(确定)?如果正常,那为什么是404?这是否意味着服务器已经收到我的数据,但无法比较数据是否正确?

我有以下组件/页面:

应用程序.vue

<template>
  <div id="app">
      <div id="nav">
      <router-link to="/">Home page</router-link> |
      <router-link to="/login">Login</router-link>
      <span v-if="isLoggedIn"> | <a @click="logout">Logout</a></span>
    </div>
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App',
  computed : {
      isLoggedIn : function(){ return this.$store.getters.isLoggedIn}
    },
  methods: {
    logout: function () {
      this.$store.dispatch('logout')
      .then(() => {
        this.$router.push('/login')
      })
    }
  },
  created: function () {
    this.http.interceptors.response.use(function (err) {
      return new Promise(function (resolve) {
        if (err.status === 401 && err.config && !err.config.__isRetryRequest) {
          this.$store.dispatch("logout")
          resolve()
        }
        throw err;
      });
    });
  },
}
</script>

LoginAnalytics.vue 在这里用户必须输入数据:手机和密码,用于授权

<template>
 <div>
   <form class="login" @submit.prevent="login">
     <h1>Sign in</h1>
     <label>Mobile</label>
     <input required v-model="mobile" type="tel" placeholder="mobile phone"/>
     <label>Password</label>
     <input required v-model="password" type="password" placeholder="Password"/>
     <hr/>
     <button type="submit">Login</button>
   </form>
 </div>
</template>
<script>
  export default {
    data(){
      return {
        mobile : "",
        password : ""
      }
    },
    methods: {
      login: function () {
        let login = this.mobile 
        let password = this.password
        this.$store.dispatch('login', { login, password })
       .then(() => this.$router.push('/secure'))
       .catch(err => console.log(err))
      }
    }
  }
</script>

Vuex 商店。这里我创建了一个 axios post 请求来联系服务器。

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
import { API_BASE_URL, TEMPORARY_TOKEN } from '../config';

Vue.use(Vuex);

export default new Vuex.Store({
  state:{
    trainings: [],
    incomings: [],
    sources: [],
    avgShedule: [],
    metro: [],
    conversion: [],
    avgIncome: [],
    status: '',
    token: localStorage.getItem('token') || '',
    user : {},
  },
  mutations:{
    auth_request(state){
      state.status = 'loading'
    },
    auth_success(state, token, user){
      state.status = 'success'
      state.token = token
      state.user = user
    },
    auth_error(state){
      state.status = 'error'
    },
    logout(state){
      state.status = ''
      state.token = ''
    },
  },
  getters:{
    isLoggedIn: state => !!state.token,
    authStatus: state => state.status,
  },
  actions:{
    login({commit}, user){
      return new Promise((resolve, reject) => {
        commit('auth_request')
        axios({
        url: `${API_BASE_URL}/analytics.auth`,
        data: user,
        method: 'POST',
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        }
      })
        .then(resp => {
          const token = resp.data.token
          const user = resp.data.user
          localStorage.setItem('token', token)
          axios.defaults.headers.common['Authorization'] = token
          commit('auth_success', token, user)
          resolve(resp)
        })
        .catch(err => {
          commit('auth_error')
          localStorage.removeItem('token')
          reject(err)
        })
      })
    },

    logout({commit}){
    return new Promise((resolve) => {
      commit('logout')
      localStorage.removeItem('token')
      delete axios.defaults.headers.common['Authorization']
      resolve()
    })
    }
  }
},
)

路由器。以下是在页面和组件之间切换的所有链接。

import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import Analytics from '@/pages/Analytics-test.vue'
import LoginAnalytics from '@/components/LoginAnalytics.vue'
import HomeAnalytics from '@/components/HomeAnalytics.vue'

Vue.use(Router)

let router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeAnalytics
    },
    {
      path: '/login',
      name: 'login',
      component: LoginAnalytics
    },
    {
      path: '/secure',
      name: 'secure',
      component: Analytics,
      meta: { 
        requiresAuth: true
      }
    },
  ]
})

router.beforeEach((to, from, next) => {
  if(to.matched.some(record => record.meta.requiresAuth)) {
    if (store.getters.isLoggedIn) {
      next()
      return
    }
    next('/login') 
  } else {
    next() 
  }
})


export default router

另外:main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router';
import store from './store'
import axios from 'axios'


Vue.config.productionTip = false

Vue.prototype.$http = axios;
const token = localStorage.getItem('token')
if (token) {
  Vue.prototype.$http.defaults.headers.common['Authorization'] = token
}

new Vue({
  store,
  router,
  render: h => h(App),
}).$mount('#app')

每次我输入正确的授权数据时,我都会在控制台中收到以下错误:

在此处输入图像描述

vue.js axios
  • 1 个回答
  • 22 Views
Martin Hope
Rasim
Asked: 2022-08-17 04:11:31 +0000 UTC

ReactJS Axios 发送多个请求

  • 0

我不明白一些事情......为什么有2个请求离开?结果,出现了 2 个答案。怎么了?

这是我的代码

import {TodoItem} from "./TodoItem";
import {useEffect, useState} from "react";
import axios from "axios";

export function TodoList() {
    const [allTodo, setAllTodo] = useState([]);

    useEffect(() => {
        axios.get(`http://127.0.0.1:8000/api/todo/`)
            .then(response => {
                response.data.forEach((todo) => {
                    setAllTodo(allTodo => [...allTodo, todo]);
                })
            })
            .catch(error => {
                console.log(error)
            })
    }, [])

    return (
        <div className="TodoList">
            {
                allTodo.map((todo, index) => {
                    return <TodoItem key={index} data={todo}/>
                }
            )}
        </div>
    );
}

reactjs axios
  • 1 个回答
  • 32 Views
Martin Hope
sc_zoo
Asked: 2022-04-26 22:56:19 +0000 UTC

如何以这种格式从 API 获取信息?

  • 0

遇到一个问题,刚接触axios,什么代码会从这种API接收数据?因为我试图做某事,这里有一个例子(但没有任何效果,啊哈):

const axios = require('axios');

async function testaxios() {

    let res = await axios.get('https://streamcraft.net/api/forum/populars');

    let test = res.data.login;

    console.log(`test: ${test}`)
}

testaxios();

响应结构(您需要登录才能进行测试):

{"populars":[{"login":"Notice","uuid":"ed3977c3-1e69-3b9b-19f3-83041c6b71f7","reputation":733},{"login":"Aleksey3275","uuid":"bb06a6e0-43fd-11ea-977d-5557488d6d86","reputation":624},{"login":"Mine03","uuid":"923680ce-cb06-e915-3226-6ab89f650691","reputation":617},{"login":"SmartLight","uuid":"254d94d0-02e2-11e9-a7c0-15ed89e3b000","reputation":602},{"login":"GizzMOO","uuid":"2e2d7650-8eea-11ea-b517-7fbff509f2eb","reputation":533},{"login":"NeoD","uuid":"c8dbe345-f2c2-0781-6f43-4cc3cfe0323f","reputation":321},{"login":"xchatos","uuid":"837805a0-5301-11e9-8aa4-47ea0e328458","reputation":308}]}

错误:

(node:38220) UnhandledPromiseRejectionWarning: Error: Request failed with status code 403
    at createError (D:\User.Data\Desktop\vbtg\node_modules\axios\lib\core\createError.js:16:15)
    at settle (D:\User.Data\Desktop\vbtg\node_modules\axios\lib\core\settle.js:17:12)
    at IncomingMessage.handleStreamEnd (D:\User.Data\Desktop\vbtg\node_modules\axios\lib\adapters\http.js:260:11)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1220:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:38220) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To
 terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:38220) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

很可能,参数根本不正确,因为到目前为止我已经从我的机器上运行了测试,所以肯定可以访问。需要更改哪些内容才能使代码正常工作?

axios
  • 1 个回答
  • 10 Views
Martin Hope
Aslero
Asked: 2022-01-18 13:52:17 +0000 UTC

如何在 asyncData axios 中显示错误?

  • 0

如何在 asyncData 中显示来自服务器的错误代码或消息 + 其他捕获错误?

export default {
  async asyncData({ $axios }) {
      const query = await $axios
        .$get(`/api/v1/shop/1/banners`)
        .then((response) => {
          return response
        })
      return {
        banners: query.banners,
        currentPage: query.current_page,
        lastPage: query.last_page,
        perPage: query.per_page,
      }
  },
  data() {
    return {
  }

所以有些东西不起作用

来自服务器的数据是这样的

{"error":false,"current_page":1,"last_page":1,"per_page":16,"banners":[]}
axios
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5