vue-08-axios-get-post-跨域

1, 安装

cnpm install axios --save

2, 在main.js中引入

import Axios from 'axios'
// 挂在在Vue上
Vue.prototype.$axios=Axios;

3, get请求: 

<script>
  export default {
    name: 'HelloWorld',
    data() {
      return {
        newsData: []
      }
    },
    // 组件创建时执行
    created() {
      // 直接参数方式
      this.$axios("http://www.wwtliu.com/sxtstu/news/juhenews.php?type=junshi&count=30")
        .then(res => {
          console.log(res);
        })
        .catch(err => {
          console.log(err)
        });

      // 间接参数方式:
      this.$axios("http://www.wwtliu.com/sxtstu/news/juhenews.php", {
        params: {
          type: 'junshi',
          count: 30
        }
      }).then(res => {
        this.newsData = res.data.result.data
        console.log(this.newsData)
      }).catch(err => {
        console.log(err)
      })

    }
  }
</script>

页面渲染

<div class="hello">

    <div>
      <ul>
        <div>
          <li v-for="news in newsData">
            <img :src="news.thumbnail_pic_s" alt="">
            <p> {{ news.title }}</p>
          </li>
        </div>
      </ul>
    </div>

  </div>

4, post 请求: 

1), axios 接受的post请求参数的格式 是 form-data 格式

?name=iwen&passwd=1234

2), x-from-urlencoded:

{name: "iwen", passwd: "abc"}

使用第三方库 qs 进行转换

<script>

  import qs from "qs"

  export default {
    name: "PostRequest",
    data() {
      return {
        postList: []
      }
    },
    create() {
      // 引入第三方库, 转变 x-form-urlencoded 格式 为 form 格式
      this.$axios.post("www.wwtliu.com/sxtstu/blueberrypai/login.php", qs.stringify({
          user_id: "wenbronk",
          password: "1234"
        })
      ).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    }
  }
</script>

5, 全局的 axios的默认值

在main.js中进行全局配置

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
// 引入
import Axios from 'axios'

Vue.config.productionTip = false

// 挂在在Vue上
Vue.prototype.$axios=Axios;

// 在之后不需要 写 网址, uri了
Axios.defaults.baseURL = 'https://api.example.com';
// https 认证
Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// 设置heads, 可以不需要qs设置 
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

6, 拦截器: 

在 thne 或者 catch 之前, 做拦截处理操作

在main.js中进行拦截

// 添加请求拦截器
Axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
Axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

进行参数校验或者 后端response校验 

 7, 跨域解决方案: 

在config的 index.js 中添加: 

    // 处理跨域
    proxyTable: {
      "/api": {
        target: "http://localhost:8080",
        changeOrigin: true,
        pathRewrite: {
          "^/api": ""
        }
      }
    },

然后在main.js中添加host 代理

import Vue from 'vue'
import App from './App'
// 引入
import Axios from 'axios'

Vue.config.productionTip = false

// 挂在在Vue上
Vue.prototype.$axios=Axios;

// 解决跨域:
Vue.prototype.HOST = '/api'

然后 在 post请求中的地址, 改写为

 this.HOST + “/login.html”

 但只能在测试阶段使用, 正式环境中需要后端解决 !!!!

 

post 请求可以使用请求拦截器的方式进行拦截

import router from './router'
import Axios from 'axios'
import qs from "qs"

Vue.config.productionTip = false

// 添加 axios
Vue.prototype.$axios = Axios
Axios.defaults.baseURL = 'https://www.wwtliu.com';
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 添加 post 请求拦截器
Axios.interceptors.request.use(function (config) {
  if (config.method == "post") {
    config.data = qs.stringify(config.data)
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
Axios.interceptors.response.use(function (response) {

  return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});

springboot 解决跨域方案: 

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置你要允许的网站域名,如果全允许则设为 *
        config.addAllowedOrigin("*");
        // 如果要限制 HEADER 或 METHOD 请自行更改
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        // 这个顺序很重要哦,为避免麻烦请设置在最前
        bean.setOrder(0);
        return bean;
    }

}

 前端: 

import Axios from 'axios'
// Vue.prototype.$axios=Axios;
// 在之后不需要 写 网址, uri了
Vue.prototype.baseURL = 'http://localhost:8000/';
// Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

const axiosIns = Axios.create({
  baseURL: Vue.prototype.baseURL,
  timeout: 10000,
  withCredentials: true, // 跨域
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Access-Control-Allow-Origin": "*",
  }
});
Vue.prototype.$axios=axiosIns;

 

posted @ 2018-10-07 18:51  bronk  阅读(1742)  评论(0编辑  收藏  举报