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就被時間管理群的伙伴語音電話叫醒了,測試云之家使用狀態,為明天的周會做好準備,未雨綢繆,謝謝!...
    泰來媽媽閱讀 206評論 0 0