Vue2從0到1(五):使用nodejs+koa2和axios實現先後臺數據通訊

前面講了環境的搭建用webpack打包vue,Vue-router,vuex的使用的使用以及Vue組件化及組件間傳值

下面講一下使用nodejs+koa提供接口,axios訪問接口,先後端數據通訊的相關內容。

11.使用nodejs+koa2提供後臺接口

npm install koa koa-router --save-dev前端

在根目錄下下新建server/index.js文件index.js:vue

const Koa = require('koa');
    const router = require('koa-router')();
    const app = new Koa();
    router.get('/', (ctx, next)=> {
        ctx.response.body = '111'
    });

    app
        .use(router.routes())
        .use(router.allowedMethods());

    app.listen(3000,()=>{
       console.log('server is start at port 3000')
    });

package.json裏面設置命令:"server":"node server index.js"
啓動服務:npm run server
瀏覽器裏面訪問localhost/3000可看到返回值node

12.設置koa容許前端跨域訪問

使用koa2-cors設置跨域
安裝npm install koa2-cors --save-devwebpack

...
    app.use(cors({
        origin: function (ctx) {
            if (ctx.url === '/test') {
                return false;
            }
            return 'http://localhost:9001';
        },
        exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
        maxAge: 5,
        credentials: true,
        allowMethods: ['GET', 'POST', 'DELETE'],
        allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
    }));
    ...

13 使用axios訪問後臺接口

安裝axios:ios

npm install axios --save

在根目錄新建server/request.js
封裝一個request函數,全部的請求都經過request函數,便於對於請求統一處理git

export default {
    post(url, data) {
        return axios({
            method: 'post',
            baseURL: BASE_URL,
            url,
            data: JSON.stringify(data),
            timeout: 10000,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                'Content-Type':"application/json",
                // 'Accept': 'application/json',
                // "charset":"utf-8"
            }
        }).then(
            (response) => {
                return checkStatus(response)
            }
            ).then(
            (res) => {
                return checkCode(res)
            }
            ).catch((e)=>{
                console.log(e)
                return new Promise((resolve, reject) => {
                    reject(e);
                })
            })
    },
    get(url, params) {
        return axios({
            method: 'get',
            baseURL: BASE_URL,
            url,
            params, // get 請求時帶的參數
            timeout: 10000,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        }).then(
            (response) => {
                return checkStatus(response)
            }
            ).then(
            (res) => {
                return checkCode(res)
            }
            )
    }
}

function checkStatus(response) {github

// loading
// 若是http狀態碼正常,則直接返回數據
if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    return response
    // 若是不須要除了data以外的數據,能夠直接 return response.data
}
// 異常狀態下,把錯誤信息返回去
return {
    status: -404,
    msg: '網絡異常'
}

}web

function checkCode(res) {vuex

// 若是code異常(這裏已經包括網絡錯誤,服務器錯誤,後端拋出的錯誤),能夠彈出一個錯誤提示,告訴用戶
if (res.status === -404) {
    let vue = new Vue;
    vue.$message({ type: 'error', message:res.msg});
}
// if (res.data && (!res.data.success)) {
//     alert(res.data.error_msg)
// }
return res

}npm

調用:
import request from '.././request.js'; 
let {data} =await request.post(options.url,data1);
let {data} =await request.get(options.url,data1);
請注意這裏踩了兩個坑:
1.設置axios.defaults.withCredentials = true   //請求時帶上cookie這樣請求時纔會帶上cookie
2.設置'Content-Type':"application/json",並JSON.stringify(data),這樣後臺才能正確接收到數據
3.當設置請求時帶上cookie時後端容許的跨域不能用"*"要說明協議+域名+端口[相關問題](https://segmentfault.com/q/1010000011878964?_ea=2792154)

請求數據效果圖:圖片描述

後面將講一下element-ui的使用

代碼託管於github 歡迎star

相關文章
相關標籤/搜索