Vue学习12----数据请求模块axios,vue跨域访问,图片上传,遇到的问题

本文介绍了在Vue项目中使用axios进行数据请求,包括基本使用步骤、Vue配置跨域访问的方法,以及解决POST请求参数问题和图片上传的实现。在遇到POST请求参数丢失导致的400错误时,通过引入qs库转换参数成功解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、基本使用
第三方提供的数据请求模块
参考文档
https://www.npmjs.com/package/axios
效果图:
在这里插入图片描述
axios 的使用 步骤:
1、安装 cnpm install axios --save
2、哪里用哪里引入 import Axios from ‘axios’;
3、使用

App.vue 代码:

<template>
  <div>
    <button @click="httpGetData()">get请求数据</button>
    <br>
    <!--渲染接口拿到的数据-->
    <ul>
      <li v-for="item in list">

        {{item.title}}
      </li>
    </ul>
  </div>
</template>

<script>
  /*

请求数据的模板
    axios  的使用
    1、安装  cnpm  install  axios --save
    2、哪里用哪里引入    import Axios from 'axios';
    3、使用
*/
  import Axios from 'axios';
  export default {
    name: 'app',
    data() {
      return {
        msg: 'Welcome to Your Vue.js App',
        list: [],
      }
    },
    methods: {
      httpGetData() {
        var api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
        Axios.get(api).then((response) => {
          this.list = response.data.result;
        }).catch((error) => {
          console.log(error);

        })
      }

    }
  }
</script>

<style lang="scss">
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }

  h1, h2 {
    font-weight: normal;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }

  a {
    color: #42b983;
  }
</style>

源码下载:
vuedemo13
https://download.csdn.net/download/zhaihaohao1/11112029

二、vue 配置跨域访问:
1.在 config -----index.js 中配置:

    // 配置路由:
    proxyTable: {
      '/api':{     //这里是公共部分,在调用接口时后面接不相同的部分,/api就相当于http://192.168.0.199:8926/api这一段
        target:'https://app.5ulm.cn',   //这里写的是访问接口的域名和端口号
        changeOrigin: true, // 必须加上这个才能跨域请求
        pathRewrite: {  // 重命名
          '^/api': '/'
        }
      },
    },

2.使用的时候,拼接路径(把配置的 https://app.5ulm.cn 拼接成api 即可)

let url = 'api'+'/app/moneyPay/merchantUpload';

三、选择图片,上传图片
选择图片:

<input class="yingyezhizhao" type="file" name="" id="jiahao" value="" name="saveFile" @change="tirggerFile($event)"/>

上传图片:

      // 上传图片
      tirggerFile (event) {
        // let url = Utils.port+'/app/receiveParticipant/businessLicenseUpload';
        // 上传图片的接口,
        let url = 'api'+'/app/moneyPay/merchantUpload';
        let self = this;
        let file = event.target.files[0]
        let param = new FormData() // 创建form对象
        param.append('file', file, file.name) // 通过append向form对象添加数据
        console.log(param.get('file')) // FormData私有类对象,访问不到,可以通过get判断值是否传进去
        let config = {
          headers: {'Content-Type': 'multipart/form-data'}
        }
       axios.post(url,param,config).then(
         response =>{
           console.log(response.data);
           if (response.data.code == 200){
             // 图片上传成功
             this.photoUrl=response.data.body.photo;
             // 图片上传成功
             this.upLoadSuccess =  '营业执照上传成功';
             Toast({
               message: '营业执照上传成功',
               position: 'bottom',
               duration: 2000
             });
           }else{
             Toast({
               message: '营业执照上传失败',
               position: 'bottom',
               duration: 2000
             });

           }
         }
       );

      },

四、遇到的坑:
post请求的时候,接口会接收不到参数,返回400错误
这时候,要qs转换一下参数即可,步骤如下:
1、引入qs (axios自带的直接引入即可)

import Qs from 'qs';//引入qs

2、请求的时候qs转换

      httpSubmit() {
        // 拿到输入框的数据
        let url = Utils.port + '/app/receiveParticipant/add';
        // let canShu =mycanshu;
        let canShu = {
          companyId: '3ec644218c2f4a40b955a93d2d8ebab8',
          name: name,
          companyName: companyName,
          phone: phone,
          businessLicense: '',
        }

        axios({
          header: {
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
            'token':'123456',
          },
          method: 'post',
          url: url,
          data: Qs.stringify(canShu),//在传参之前先用qs.stringify转化一下格式
          responseType: 'json'
        }).then((response) => {
          console.log(response);
          if (200 && response.data.message == '添加参与者成功') {
            // 跳转到助力成功页面
            this.$router.push({name: 'ZhuLiSuccess'});
          } else {
            Toast({
              message: response.data.message,
              position: 'bottom',
              duration: 2000
            });
          }
        }).catch((err) => {
          console.log(err)
        })
      }

OK,了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值