前端常用获取后端请求方法(request·axios)

1.uni-app request请求

uni.request({
			url: 'http://localhost/myUniApp/php/login.php', //仅为示例,并非真实接口地址。
			data: {//参数
					rawData: rawData,
					code: loginRes.code
				},
			header: {
					'custom-header': 'hello' //自定义请求头信息
				},
            method:'POST'//请求方式  或GET
			success: res => {
					console.log('返回', res.data);
						}
			});

2.axios请求方法,以及解决跨域

安装 并在src/main.js配置 axios

npm install axios --save-dev   安装
import axios from 'axios'      引入 axios
Vue.prototype.$axios= axios    将axios绑定给vue成为一个属性

常用方法例子

Get 方法 params传递参数
this.$axios.get(url, {
    params: {
      // get方法params传递参数
      a: '1'
    }
  })
  .then(response => {
    //成功返回
    console.log(response);
  })
  .catch(error => {
    //失败返回
    console.log(error);
  });

Post 方法 传参数据必须放在消息主体中

this.$axios.post(url, {a: '1'})
  .then(response => {
    //成功返回
    console.log(response);
  })
  .catch(error => {
    //失败返回
    console.log(error);
  });

axios底层方法

this.$axios({
  method: "get",   //请求方法 [get/post]
  url: 'https://api.apiopen.top/getImages', // 请求地址
  params: {
    a: '1' // 请求参数
  }
})
.then(response => {
  //成功返回
  console.log(response);
})
.catch(error => {
  //失败返回
  console.log(error);
});

跨域请求代理

1、打开config/index.js 找到
module.exports{
    dev: {
        proxyTable{},
   }
}
2  proxyTable{},改成
   /*配置跨域*/
proxyTable: {
      '/api': {
        target: 'https://api.apiopen.top/getJoke', //设置你调用的接口域名和端口号 别忘了加http
        changeOrigin: true,  //如果接口跨域,需要进行这个参数配置
        secure: false,  // 如果是https接口,需要配置这个参数
        pathRewrite: {
          '^/api': ''//这里理解成用‘/api’代替target里面的地址,后面组件中我们调用接口时直接用api代替
        }
      }
    }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

淡忘_cx

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

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

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

打赏作者

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

抵扣说明:

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

余额充值