笔记:vue2简单引用接口数据:$http、 axios、ajax

一、$http(未尝试)

this.$http.get('/url',[options]).then(successCallback,errorCallback);
this.$http.post('/url',[body],[options]).then(successCallback,errorCallback);

二、 axios

1、安装 npm i axios vue-axios --save
2、main.js中添加:
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);//注意需要先注册VueAxios

3、获取接口数据

this.axios({
  url:'http://...../data'
}).then(res=>{
  console.log(res);
})

三、axios方式解决跨域问题:

例接口链接:https://hlj.*******.cn/proxy/getPlans?type=1&&size=100

1、修改vue.config.js文件

        配置代理proxy,修改vue.config.js文件后需要重启项目

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  publicPath: './',/**打包后的路经重定向**/
  devServer: {
    //配置代理(解决跨域)
    proxy:{
      '/api':{                     //这个就是的标识,当接口用 api 开头才用代理
        target:'https://hlj.*****.cn/',       //需代理的后端接口
        // pathRewrite:{ '^/api':'/'}, //重写匹配的字段。把/api 转为 /
        pathRewrite:{ '^/api':''}, //重写匹配的字段。把/api 转为 空
        changeOrigin:true                //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
      }
    }
  },
})
2、获取接口数据
this.axios.get('/api/proxy/getPlans',{
    params:{
        type: 1,
        size: 100,
    }
}).then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
})
3、上传服务器后可能需要配置nginx反向代理

        location /api/ {rewrite ^/api/(.*) /$1 break;  proxy_pass https://hlj.*****.cn/;}

server
{
    listen 80;
    server_name xxxxx.cn; #本机主机名
    #跨域请求代理配置
    location /api/ {
      rewrite ^/api/(.*) /$1 break;
      proxy_pass https://hlj.*****.cn/;
    }
    ............

 四、axios的基本使用

1、提交数据post
this.axios.post(('/user/login'),{
    username:'rourou',
    password:'1225'
}).then((res)=>{
    this.$cookie.set('userId',res.id,{expires:'1M'});
    this.$router.push('/index')//路由跳转
}).catch((err)=>{
    console.log(err);
})   
2、读取数据get
  •  并发请求,通用模式,方式可定义为get或post
axios({
    method:'get',
    url:'/product',
    data:{
        id:'1225',
    }
}).then(res=>{
    this.product=res
}).catch(err=>{
    console.log(err);
})
  • 直接在url地址中传入参数(传入动态路由
this.axios.get((`/products/${id}`)).then((res)=>{//通过id调用商品接口
    this.product=res
}).then(res=>{
this.product=res
}).catch((err)=>{
    console.log(err);
})  
  • params进行传参
this.axios.get('/products',{
    params:{
        id:'1234'
    }
}).then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
})

五、ajax(未尝试)

1、安装jQuery   npm install jquery --save
2、发起AJAX请求
this.$.ajax({
  url: '/api/data',
  type: 'GET',
  dataType: 'json'
}).done(response => {
  console.log(response)
}).fail(error => {
  console.error(error)
})
3、跨域

        dataType: 'jsonp'

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值