美文网首页
Vue网络请求与跨域配置

Vue网络请求与跨域配置

作者: MillerWang | 来源:发表于2019-03-13 08:40 被阅读9次

一、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);
            });
    }

相关文章

网友评论

      本文标题:Vue网络请求与跨域配置

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