第十章:vue2中axios請求服務端資料
阿新 • • 發佈:2019-02-05
一、關於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
三、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:'水滸傳'
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); }) } }