Vue网络请求与跨域配置

一、Fetch配置 https://blog.csdn.net/qq_42492055/article/details/82593692

1、在config配置文件中的index.js中的跨域区域中配置proxyTable

proxyTable: {
      '/apis':{    //名字自己定义,以后接口的域名用他来替换
        target: 'http://cc.lzjoy.com/', //接口域名
        changeOrigin: true, //是否跨域
        pathRewrite: {
          '^/apis': ''  //需要rewrite重写
        }
      }
    },

2、发起网络请求

    //1、get请求
    created(){
      console.log("请求数据")
      fetch("/apis?urlparam=pad/index/getindexdata", {
        method: "get",
        headers:{
          "Content-Type": "application/json",
        },
      }).then(result=>{
        return result.json()
      }).then(result=>{
        console.log(result)

      }).catch(err=>{
        alert(err)
      })
    }
    
    //2、post请求
    created(){
      console.log("请求数据")
      fetch("/apis?urlparam=pad/index/getindexdata", {
        method: "post",
        headers:{
          "Content-Type": "application/json",
        },
        //这里要放要上传的参数
        body: JSON.stringify({name: "abc", phone: "123456"})
      }).then(result=>{
        return result.json()
      }).then(result=>{
        console.log(result)
      }).catch(err=>{
        alert(err)
      })
    }

二、axios配置

https://blog.csdn.net/qq_42492055/article/details/82593692

0、安装axios

npm install axios

1、在config配置文件中的index.js中的跨域区域中配置proxyTable

    proxyTable: {
      '/apis':{    //名字自己定义,以后接口的域名用他来替换
        target: 'http://cc.lzjoy.com/', //接口域名
        changeOrigin: true, //是否跨域
        pathRewrite: {
          '^/apis': ''  //需要rewrite重写
        }
      }
    },

2、在程序入口 main.js文件中引入并配置axios

import Axios from 'axios'

// 设置axios
Vue.prototype.$axios = Axios
// Axios.defaults.baseURL = '/apis'
Axios.defaults.headers.post['Content-Type'] = 'application/json'

3、发起请求

    //1、get请求
    created(){
        console.log("页面加载")
        this.$axios.get("/apis?urlparam=pad/index/getindexdata")
            .then(res=>{
              console.log(res)
              alert(res)
            })
            .catch(err=>{
              console.log(err)
            })
      }
      //2、 post请求 name、phone是要发送的参数
    created(){
        this.$axios.post('/apis?urlparam=pad/index/getindexdata', {
              name: 'Fred',
              phone: '123456'
            })
            .then(function (response) {
              console.log(response);
              alert(response)
            })
            .catch(function (error) {
              console.log(error);
            });
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天我是来台湾学习参观的第11天,我从老师的身上学到了很多,首先就是不要给自己贴标签,如果你觉得自己是这样的,那...
    日光倾城_625c阅读 354评论 0 0
  • 感恩今天早上6:30就被时间管理群的伙伴语音电话叫醒了,测试云之家使用状态,为明天的周会做好准备,未雨绸缪,谢谢!...
    泰来妈妈阅读 204评论 0 0