当前位置:   article > 正文

在 Vue 3 中使用 Axios 发送 POST 请求

在 Vue 3 中使用 Axios 发送 POST 请求

Vue 3 中使用 Axios 发送 POST 请求需要首先安装 Axios,然后在 Vue 组件或 Vuex 中使用它。以下是一个简单的安装和使用案例:

安装 Axios

你可以使用 npm 或 yarn 来安装 Axios:

  1. npm install axios
  2. # 或者
  3. yarn add axios

使用 Axios 发送 POST 请求

  1. 在 Vue 组件中使用 Axios

首先,在你的 Vue 组件中导入 Axios:

  1. <template>
  2. <div>
  3. <button @click="sendPostRequest">发送 POST 请求</button>
  4. </div>
  5. </template>
  6. <script>
  7. import axios from 'axios';
  8. export default {
  9. methods: {
  10. async sendPostRequest() {
  11. try {
  12. const response = await axios.post('https://example.com/api/endpoint', {
  13. key1: 'value1',
  14. key2: 'value2'
  15. });
  16. console.log(response.data);
  17. } catch (error) {
  18. console.error('Error sending POST request:', error);
  19. }
  20. }
  21. }
  22. };
  23. </script>

在上面的例子中,当点击按钮时,sendPostRequest 方法会被调用,它会向指定的 URL 发送一个 POST 请求,并携带一些数据。如果请求成功,它会打印响应数据;如果请求失败,它会打印错误信息。

  1. 在 Vuex 中使用 Axios

如果你更倾向于在 Vuex 中处理 API 请求,你可以这样做:

首先,在你的 Vuex store 中导入 Axios:

  1. import axios from 'axios';
  2. export default new Vuex.Store({
  3. actions: {
  4. async fetchData({ commit }) {
  5. try {
  6. const response = await axios.post('https://example.com/api/endpoint', {
  7. key1: 'value1',
  8. key2: 'value2'
  9. });
  10. commit('setData', response.data);
  11. } catch (error) {
  12. console.error('Error fetching data:', error);
  13. }
  14. }
  15. },
  16. mutations: {
  17. setData(state, data) {
  18. state.data = data;
  19. }
  20. },
  21. state: {
  22. data: null
  23. }
  24. });

然后,在你的 Vue 组件中调用这个 action:

  1. <template>
  2. <div>
  3. <button @click="fetchData">获取数据</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. methods: {
  9. fetchData() {
  10. this.$store.dispatch('fetchData');
  11. }
  12. },
  13. computed: {
  14. data() {
  15. return this.$store.state.data;
  16. }
  17. }
  18. };
  19. </script>

在这个例子中,当点击按钮时,fetchData 方法会被调用,它会触发 Vuex 中的 fetchData action。这个 action 会发送 POST 请求并更新 Vuex store 中的数据。然后,你可以通过计算属性来访问这些数据。

创建一个 Axios 实例并配置一些基础选项

  1. const instance = axios.create({
  2. baseURL: 'https://some-domain.com/api/',
  3. timeout: 1000,
  4. headers: {'X-Custom-Header': 'foobar'}
  5. });
  6. const onSubmit = async () => {
  7. try {
  8. const response = await instance.post('/customer_info', {
  9. inputValue // 注意判断inputValue是否已经是对象,如果是删除{}
  10. });
  11. console.log(response.data);
  12. } catch (error) {
  13. if (error.response) {
  14. // 请求已发出,服务器也返回了状态码,但状态码不在 2xx 范围内
  15. console.error('Error sending POST request:', error.response.data);
  16. // 可以根据 error.response.data 中的错误信息向用户展示具体的提示
  17. } else if (error.request) {
  18. // 请求已发出,但没有收到任何回应
  19. console.error('The request was made but no response was received:', error.request);
  20. } else {
  21. // 在设置请求时触发了一个错误
  22. console.error('Error setting up the request:', error.message);
  23. }
  24. }
  25. };

请注意以下几点:

  1. baseURL 在 instance 创建时已经被设置了,所以在调用 instance.post 时,您只需要提供相对于 baseURL 的路径(例如 /customer_info),而不是完整的 URL。

  2. 确保 inputValue 变量在 onSubmit 函数的作用域内是可访问的,并且包含了您想要发送的数据。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/416935
推荐阅读
相关标签
  

闽ICP备14008679号