Vue2.x axios发送post请求

本文介绍了如何在Vue2.x项目中使用axios发送POST请求,包括通过npm安装axios,配置main.js,以及在vue组件的script部分编写代码进行请求操作。还提供了实际操作的演示图作为参考。
摘要由CSDN通过智能技术生成

安装axios

$ npm install axios
//使用淘宝源
$ cnpm install axios
//或者使用cdn:一般不使用
script src=“https://unpkg.com/axios/dist/axios.min.js

配置main.js

以下代码为之前开发的项目中的配置代码 可供参考

	// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Axios from 'axios'
import ElementUI from 'element-ui'



Axios.defaults.headers.post['Content-Type']='application/json'
Vue.config.productionTip = false
Vue.prototype.$axios=Axios


//请求拦截器
Axios.interceptors.request.use(function(config)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过在发送 POST 请求时,在请求头中添加一个标记,然后在接收响应时再移除这个标记。在 Vue.js 中,可以使用 Axios 的拦截器来实现这个功能。 首先,在 Vue.js 中引入 Axios: ```javascript import axios from 'axios'; ``` 然后,定义一个 Axios 实例: ```javascript const axiosInstance = axios.create({ baseURL: 'http://example.com/api', timeout: 5000, headers: { 'Content-Type': 'application/json' } }); ``` 接下来,在 Axios 实例中添加请求拦截器: ```javascript axiosInstance.interceptors.request.use(config => { // 在请求头中添加一个标记 config.headers['X-Loading'] = true; return config; }, error => { return Promise.reject(error); }); ``` 在请求拦截器中,可以在请求头中添加一个名为 X-Loading 的标记。这个标记的值可以是任意值,我们可以通过这个标记来判断是否需要显示加载动画。 接着,在 Axios 实例中添加响应拦截器: ```javascript axiosInstance.interceptors.response.use(response => { // 移除请求头中的标记 delete response.config.headers['X-Loading']; return response; }, error => { delete error.config.headers['X-Loading']; return Promise.reject(error); }); ``` 在响应拦截器中,可以移除请求头中的 X-Loading 标记。 最后,在 Vue.js 中使用 Axios 发送 POST 请求时,可以在发送请求前显示加载动画,在接收响应时隐藏加载动画: ```javascript export default { data() { return { loading: false }; }, methods: { async submitForm() { try { this.loading = true; await axiosInstance.post('/login', { username: 'test', password: 'test' }); this.loading = false; } catch (error) { this.loading = false; console.log(error); } } } }; ``` 在 Vue.js 组件中,可以定义一个 loading 变量来控制加载动画的显示和隐藏。在调用 Axiospost 方法时,可以先将 loading 变量设置为 true,表示正在加载中。在接收响应时,再将 loading 变量设置为 false,表示加载完成。如果发生错误,也需要将 loading 变量设置为 false。 在模板中可以使用 loading 变量来控制加载动画的显示和隐藏: ```html <template> <div> <form @submit.prevent="submitForm"> <input type="text" v-model="username" placeholder="Username"> <input type="password" v-model="password" placeholder="Password"> <button type="submit">Submit</button> </form> <div v-if="loading">Loading...</div> </div> </template> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值