axios網絡交互應用-Vue

file

做者 | Jesksoncss

來源 | 達達前端小酒館前端

<template>
 <div id="app">
 <input type="text" placeholder="name" v-model="user.name">
 <input type="text" placeholder="age" v-model="user.age">
 <button type="button" class="btn" @click="btn.clickcallback">
 {{btn.text}}
 </button>
 <table class="table">
  <thead>
   <tr>
    <th>id</th>
    <th>name</th>
    <th>操做</th>
   </tr>
  </thead>
  <tbody>
   <tr v-for="item,index) in users" :kkey="index">
    <td scope="row">{{item.id}}</td>
    <td>{{item.name}}</td>
 
    <td>
     <a class="btn" href="#" role="button"
     @click.prevent="edituser(index)">編輯</a>
     <a class="btn" href="#" role="button" @click.prvent="deleteuser(index)">刪除</a>
     </td>
    </tr>
    </tbody>
    </table>
    </div>
    </template>
    <script>
    import "bootstrap/dist/css/boostrap.css";
    export default {
     name: 'app',
     data(){
     return {
      users: [],
      // 添加數據
      user: {},
      editindex: -1,
      btn: {
       text: '添加用戶',
       clickcallback: this.adduser
      }
     };
    },
    methods: {
     adduser(){
     const app = this;
     axios.post('/api/users',this.user).then(res=>{
     app.users.push(res.data.data);
     app.user ={};
    });
   },
   edituser(index){
   this.editindex = index;
   this.user = this.users(index);
   this.btn={
   text: '編輯用戶',
   clickcallback: this.doedituser
   };
  },
  doedituser(){
  axios.put('/api/users/'+this.users[this.editindex].id,this.user).then(res => {
  app.editindex=-1;
  app.user ={};
  app.btn={
  text: "添加用戶",
  clickcallback: app.adduser
 };
});
},
// 刪除用戶
deleteuser(index) {
const app = this;
axios.delete('/api/users/'+this.users[index].id).then(function(res){
if(res.data.status){
app.users.splice(index,1);
}
};
}
},
// axios網絡請求獲取數據
created: function(){
const app = this;
axios.get('/api/users').then(res=>{
app.users=res.data.data;
})
}
}
</script>

Axios 是一個基於 promise 的 HTTP 庫,能夠用在瀏覽器和 node.js 中node

能夠提供如下服務:ios

一、從瀏覽器中建立XMLHttpRequests
二、從node.js建立http請求
三、支持PromiseAPI
四、攔截請求和響應
五、轉換請求數據和響應數據
六、取消請求
七、自動轉換JSON數據
八、客戶端支持防護XSRFweb

Vue安裝axios插件的命令是?

axios的安裝: ajax

安裝命令; npm install axios算法

get: 通常多用於獲取數據 npm

post: 主要提交表單數據和上傳文件bootstrap

put對數據所有進行更新axios

該請求和post相似,只是請求方法不一樣

patch只對更改過的數據進行更新

該請求和post相似,只是請求方法不一樣

delete刪除請求

參數能夠放在url上,也能夠和post同樣放在請求體中

axios是對ajax請求的封裝

原生ajax請求實現

//步驟一:建立異步對象
var ajax = new XMLHttpRequest();
//步驟二:設置請求的url參數,參數一是請求的類型,參數二是請求的url,能夠帶參數,動態的傳遞參數starName到服務端
ajax.open('get', 'http://。。。');
//步驟三:發送請求
ajax.send();
//步驟四:註冊事件 onreadystatechange 狀態改變就會調用
ajax.onreadystatechange = function () {
    if (ajax.readyState == 4 && ajax.status == 200) {
        //步驟五 若是可以進到這個判斷 說明 數據 完美的回來了,而且請求的頁面是存在的
        console.log(ajax.responseText);//輸入相應的內容
    }
}
//建立異步對象  
var xhr = new XMLHttpRequest();
//設置請求的類型及url
//打開xhr
xhr.open('post', 'http://。。。');
//post請求必定要添加請求頭才行否則會報錯
//設置請求頭,請求頭的設置必須在xhr打開以後,而且在send以前
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//發送請求
xhr.send();
xhr.onreadystatechange = function () {
    // 這步爲判斷服務器是否正確響應
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText);
    }
};
// 給axios設置baseURL
axios.defaults.baseURL = ' https:、api';

let url = /film/getList';
axios.get(url).then(res => {
    console.log(res);
})
// 設置請求頭
axios.defaults.headers['sessionToken'] = 'asd234';

同源策略:

跨域的產生來源於現代瀏覽器所通用的‘同源策略’,所謂同源策略,是指只有在地址的:
  1. 協議名
  2. 域名
  3. 端口名

均同樣的狀況下,才容許訪問相同的cookie、localStorage或是發送Ajax請求等等。若在不一樣源的狀況下訪問,就稱爲跨域。

如何解決axios跨域問題?

解決辦法:

服務器(後臺)設置容許跨域

瀏覽器設置跨域

經過代理容許跨域

header('Access-Control-Allow-Origin:*');
//容許全部來源訪問 
header('Access-Control-Allow-Method:POST,GET');
//容許訪問的方式

攔截器分爲 :

請求(request)攔截器和 響應(response)攔截器

經過axios.create建立一個axios實例

// 建立axios對象

let $axios = axios.create({
    baseURL: 'http://。。。'
})

請求(request)攔截器

// 發送前攔截 request-請求
$axios.interceptors.request.use(res=> {
    // 添加請求頭
    res.headers.sessionToken = 'as423424..';
    return res;
})

響應(response)攔截器

// 數據返回後的攔截 response-響應
$axios.interceptors.response.use(function (res) {
    if (res.data.code === '200') {
        return res.data;
    } else {
        alert(res.data.msg);
    }
}, function (error) {
    alert('網絡異常');
})

記得分享哦!

❤️ 不要忘記留下你學習的腳印 [點贊 + 收藏 + 評論]

做者Info:

【做者】:Jeskson
【原創公衆號】:達達前端小酒館。
【福利】:公衆號回覆 「資料」 送自學資料大禮包(進羣分享,想要啥就說哈,看我有沒有)!
【轉載說明】:轉載請說明出處,謝謝合做!~

大前端開發,定位前端開發技術棧博客,PHP後臺知識點,web全棧技術領域,數據結構與算法、網絡原理等通俗易懂的呈現給小夥伴。謝謝支持,承蒙厚愛!!!


若本號內容有作得不到位的地方(好比:涉及版權或其餘問題),請及時聯繫咱們進行整改便可,會在第一時間進行處理。


請點贊!由於大家的贊同/鼓勵是我寫做的最大動力!

歡迎關注達達的CSDN!

這是一個有質量,有態度的博客

前端技術棧

相關文章
相關標籤/搜索