Vue中使用Axios调用post方法报错:Cannot read property 'post' of undefined
Hey Chris, let's fix that TypeError you're hitting with Axios in your Vue method. The core issue here is that your Vue instance doesn't have access to axios via this.axios—that's exactly why it's throwing "Cannot read property 'post' of undefined". Here's how to get your sign-in request working smoothly:
Step 1: Make sure Axios is properly set up
First, confirm you've added Axios to your project:
- If using npm/yarn: Run
npm install axios --save(oryarn add axios) - If using a CDN: Add this script tag before your Vue script:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Step 2: Access Axios correctly in your Vue method
You have two straightforward options to use Axios in your Vue instance:
Option 1: Globally mount Axios to Vue's prototype (reusable across all components)
Add this line before initializing your Vue instance. This lets every component access Axios via this.$axios:
Vue.prototype.$axios = axios;
Then update your signin method to use this.$axios instead of this.axios:
signin:function(){ console.log(this.email + ' ' + this.code); // Fixed the typo here (was this.access) let url = '../App/testConnection.php'; this.$axios.post(url, {email:this.email, code:this.code}) .then((response) =>{ console.log(response); }) .catch(function (error) { console.log(error); }); }
Option 2: Import Axios directly in your method (for single-component use)
If you're working in a modular environment (like Vue CLI), import Axios at the top of your script:
import axios from 'axios';
Then use it without this in your method:
signin:function(){ console.log(this.email + ' ' + this.code); let url = '../App/testConnection.php'; axios.post(url, {email:this.email, code:this.code}) .then((response) =>{ console.log(response); }) .catch(function (error) { console.log(error); }); }
Bonus: Clean up minor code issues
I noticed two small things in your original code that are worth fixing:
- The
dataobject has an extra comma aftercode:''(it won't break things, but it's cleaner to remove) - You tried logging
this.access, but that property doesn't exist in yourdata—I assume you meantthis.code
Here's the full corrected code using the global mount approach:
// Load Axios and Vue via CDN first <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script> Vue.prototype.$axios = axios; new Vue({ el:'#app', data:{ email:'', code:'' }, methods:{ signin:function(){ console.log(this.email + ' ' + this.code); let url = '../App/testConnection.php'; this.$axios.post(url, {email:this.email, code:this.code}) .then((response) =>{ console.log(response); }) .catch(function (error) { console.log(error); }); } } }) </script>
内容的提问来源于stack exchange,提问作者ChrisJ

