美文网首页
(十二)axios来发送数据

(十二)axios来发送数据

作者: 我拥抱着我的未来 | 来源:发表于2018-04-15 22:26 被阅读0次

    本节知识点

    • 利用axios来发送数据和接受数据

    axios 下的Get 请求 必须有params

    axios.get(url, {
      params: { 'key': 'value' }
    }).then(function (response) {
      alert(''.concat(response.data, '\r\n', response.status, '\r\n', response.statusText, '\r\n', response.headers, '\r\n', response.config));
    }).catch(function (error) {
      alert(error);
    });
    

    具体步骤 第一种跨域

    1. 安装axios
    npm i axios -S
    

    2.安装qs模块

    npm i qs -S
    

    2.在组件里面引入模块

    import axios from 'axios'
     import qs from 'qs';
    

    3.POST组件里面可以直接

      methods:{
        click1:function(){
          var params = {name:"张三",sex:"男"};
          axios.post('http://localhost:3000/post',qs.stringify(params))
            .then(function (response) {
              console.log(response.data);
            })
            .catch(function (error) {
              console.log(error);
            });
        }
      }
    

    4.GET组件里面可以直接 必须最外层包裹一层params或者直接在地址栏里面拼接

      mounted () {
        let id = this.$route.params.id
        console.log(id)
        let data = {
          params: {
            id: id
          }
        }
        axios.get('/api/detail.json', data).then(this.getdata)
      },
    

    还有一种是安装JSONP实现跨域请求

    (1) 先安装

    $ npm install jsonp --save
    

    (2) 然后写代码

    const jsonp = require('jsonp');
    
    jsonp('http://www.example.com/foo', null, (err, data) => {
      if (err) {
        console.error(err.message);
      } else {
        console.log(data);
      }
    });
    

    自己封装一个axios请求

    封装函数

        fengzhuang (url, obj) {
          return new Promise(
            (resolve, reject) => {
              axios.post(url, qs.stringify(obj)).then((res) => { resolve(res) }).catch((res) => { reject(res) })
            }
          )
        }
    

    调用的时候

      let fashe = Object.assign({}, this.data);
     this.fengzhuang("http://xxxxx.com/login", fashe ).then(function (res) { console.log(res) })
    

    相关文章

      网友评论

          本文标题:(十二)axios来发送数据

          本文链接:https://www.haomeiwen.com/subject/ksmjkftx.html