美文网首页技术无边界
vue cli2.0版本解决前端请求跨域的方法

vue cli2.0版本解决前端请求跨域的方法

作者: zkzhengmeng | 来源:发表于2019-06-27 15:48 被阅读0次

1、打开config/index.js,在proxyTable中添写如下代码:

proxyTable: {
            '/apis': { //使用"/api"来代替"http://f.apiplus.c" 
                // 测试环境
                target: 'https://www.baidu.com/', // 接口域名
                changeOrigin: true, //是否跨域
                pathRewrite: {
                    '^/apis': 'https://www.baidu.com/' //需要rewrite重写的,
                }
            }
        },

2、在main.js中配置以下如下代码:

import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import qs from 'qs'
Vue.config.productionTip = false
Vue.prototype.$http = axios
Vue.prototype.$http = axios.create({
    headers: {'Content-Type': 'application/json;charset=UTF-8'}, //后台需要格式配置
    baseURL: '/apis', //开发环境请求地址
     //baseURL: 'https://www.baidu.com/', //生产环境请求地址
         transformRequest: [function (data) { //数据格式转换
         data = JSON.stringify(data)
                 console.log(data)
           return data
         }]
         
    })
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

3、在项目中具体使用案例:


1.axios方式请求案例
  this.$http.post('system/getCarInfo', {
        "userId": "1001",
                "usermane":"张小龙"
      }).then((res) => {
        console.log(res)
      })

2.fecth方式请求案例
    fetch("/apis/test/testToken.php", {
          method: "POST",
          headers: {
          "Content-type": "application/json",
          token: "f4c902c9ae5a2a9d8f84868ad064e706"
        },
        body: JSON.stringify(data)
      })
      .then(res => res.json())
      .then(data => {
        console.log(data);
      });

相关文章

网友评论

    本文标题:vue cli2.0版本解决前端请求跨域的方法

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