在vue.js框架给后端发送请求

  在一篇文章中,我们说了如果在后端接收POST请求(JSON类型和x-www-form-urlencoded类型),不过使用的是Postman来模拟前端发送请求的。
这篇文章将展示使用在vue.js框架中如何发送请求。
  Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。Axios官方说明文档

var map = {			//JSON数据		名称-值对
   "username":this.user.name,
    "password":this.user.pass
}
this.$axios.post(
    '/login'		//自己提供的API接口  如果自己没有写的话,可以直接写 提交的url(例如:http://localhost:8080/BookShopOfSpring2/api/getAllBookByType)
    ,map)

.then((response)=>{
    flag=response.data;
})
.then( (res)=>{
    if (flag==true) { 
    	 this.$notify({
            type: 'success',
            message: '欢迎用户'+this.user.name,
            duration: 3000
        })
    } else {
        this.$message({
            type: 'error',
            message: '用户名或密码错误',
            showClose: true
        })
    }
})
.catch( (err)=>{
    console.log(err);
})

下面这种形式的也可以:

axios.post('/user', {			//官方格式
    firstName: 'Fred',		
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

要注意的是 axios 默认编码类型是 application/json。如果想要修改默认的编码方式,在vue.js框架中的main.js文件中,添加:

import  axios from 'axios'			//引入axios
axios.defaults.baseURL = 'https://api.example.com';			//设置默认请求地址
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;	//Web API 验证
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';	//设置默认编码方式为

也可以直接在请求中设置请求头:

this.$axios({
	method: 'post',
	url: 'http://www.17huo.com/tusou/deeplorSearch.html',
	headers: {
	  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
	},
	data: { imgFile: url },		//data是添加到请求体(body)中的, 用于post请求。
//	params: { imgFile: url }	params是添加到url的请求字符串中的,用于get请求。
}).then(data => {
console.log(data)
})
  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云淡风轻~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值