vue中使用axios

  1. 安装axios
    npm install vue-axios --save
  2. 安装成功后,在main.js页面引用:

    import axios from 'axios'
    Vue.prototype.$axios = axios    //全局注册,使用方法为:this.$axios
    import Qs from 'qs'
    Vue.prototype.Qs = Qs    //全局注册,使用方法为:this.Qs
    
  3. 发送请求

    this.$axios({
          headers: {
            'accessToken': 'token'
          },
          method:'post',
          url:'http://ermsgapi/api.php',
          data: this.Qs.stringify({'api':'getCatalog'})
        }).then((response) =>{          //这里使用了ES6的语法
            console.log(response.data.data)       //请求成功返回的数据
        })
  4. php获取
     

    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("Access-Control-Allow-Headers: Content-Type, accessToken");
    
    $api=$_POST["api"];
    echo $api;
    
    $header=get_all_headers();
    $accessToken=$header["accesstoken"];
    echo $accessToken;
    
    /**
     * 获取自定义的header数据
     */
    function get_all_headers(){
      // 忽略获取的header数据
      $ignore = array('host','accept','content-length','content-type');
      $headers = array();
      foreach($_SERVER as $key=>$value){
        if(substr($key, 0, 5)==='HTTP_'){
          $key = substr($key, 5);
          $key = str_replace('_', ' ', $key);
          $key = str_replace(' ', '-', $key);
          $key = strtolower($key);
          if(!in_array($key, $ignore)){
            $headers[$key] = $value;
          }
        }
      }
      return $headers;
    }

你可能感兴趣的:(web前端,vue.js,javascript,前端)