1. 程式人生 > >第十章:vue2中axios請求服務端資料

第十章:vue2中axios請求服務端資料

中文文件

一、關於axios的安裝

  • 1、利用npm安裝npm install axios --save
  • 2、利用bower安裝bower install axios --save
  • 3、直接利用cdn引入<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

二、關於get請求資料

  • 1、直接請求資料

    axios.get('/static/data.json').then(res=>{
        console.log(res);
        ....
    }).catch(error=>console.log(error));
  • 2、帶引數的請求方式

    axios.get('/static/data.json',{params:{id:123}}).then(res=>{
        console.log(res);
        ....
    }).catch(error=>console.log(error));

二、關於post請求資料

  • 1、直接請求

    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
    }).then(function (response) {
        console.log(response);
    }).catch(function
    (error) {
    console.log(error); });

三、vue-cli構建專案中利用axios請求資料處理跨域的問題

  • 1、vue-cli構建專案
  • 2、伺服器資料介面

    'use strict';
    const express = require("express");
    const app = express();
    let obj = {
        info:'success',
        code:200,
        booknames:[
            {id:0,bookname:'三國演義',author:'羅貫中'},
            {id:1,bookname:'水滸傳'
    ,author:'施耐庵'}, {id:2,bookname:'西遊記',author:'吳承恩'}, {id:3,bookname:'紅樓夢',author:'曹雪芹'}, ] }; app.get('/',(req, res) => { res.json(obj); }) app.get('/book',(req, res) => { res.json(obj); }) app.listen(3000);
  • 3、設定代理(在config->index.js)中

    // 配置代理  
    proxyTable: {
        '/api':{  // api為匹配項
            target:'http://localhost:3000/', // 設定代理目標
            changeOrigin: true,
            pathRewrite: {  // 重寫路徑
              '^/api': '/'
            }
        }
    },
  • 4、請求資料

    import axios from 'axios';
    export default {
        name: 'app',
        mounted(){
            axios.get('/api/book').then(res=>{
                console.log('第一條資料:',res);
            })
            axios.get('/api').then(res=>{
                console.log('第二條資料:',res);
            })
        }
    }