在Axios.get中调用Axios.put失效,提示axios未定义求协助
Hey there! Let's break down the two key issues in your code and fix them step by step.
1. Why you're seeing "axios is not defined"
This error almost always means Axios isn't properly imported or registered in your component/project. Since your code uses this (looks like a Vue component), here are the two common fixes:
Option 1: Local import in your component
Add this line at the top of your component's <script> section to import Axios directly into the file:
import axios from 'axios'
Option 2: Global registration (for Vue 2)
If you want to use Axios across all components without importing it every time, register it in your main.js file:
import Vue from 'vue' import axios from 'axios' Vue.prototype.$axios = axios
Then in your component, replace axios with this.$axios:
this.$axios.get(REQUESTID_URL + reqId) // ... this.$axios.put(REQUEST_URL + reqId, { /* ... */ })
2. Fixing your async logic bug
Even if you fix the Axios error, your current code has a critical issue: the axios.put runs before the axios.get finishes. Since get is asynchronous, this.collaboId, this.beginDate, etc., won't have their updated values when the PUT request sends.
Move the PUT request inside the then() block of the GET request to ensure you're using fresh data:
getAbsencesByRequestId(reqId) { axios.get(REQUESTID_URL + reqId) .then(response => { this.collaboId = response.data[0].collabId; this.beginDate = response.data[0].startDate; this.finishDate = response.data[0].endDate; this.reason = response.data[0].type; // Now execute PUT after data is fetched return axios.put(REQUEST_URL + reqId, { collabId: this.collaboId, startDate: this.beginDate, endDate: this.finishDate, status: 'VALIDATED', type: this.reason }); }) .then(putResponse => { console.log('Request updated successfully:', putResponse.data); }) .catch(error => { // Handle both GET and PUT errors here console.error('Request failed:', error.response?.status || error.message); }); }
I also added a .catch() for the PUT request to catch any update failures, which helps with debugging.
内容的提问来源于stack exchange,提问作者Jinx59

