標籤:index.php env 取數 use 部署伺服器 tput 方法調用 headers error
1. 實現效果
以get方法向http://192.168.32.12:8080/users 發起請求、擷取資料並進行處理
this.apiGet(‘/users‘, {}) .then((res) => { console.log(res) }, (err) => { console.log(err) })
2. 實現步驟一之佈建網域名首碼
2.1 安裝axios
cnpm install axios --save
2.2 配置webpack.base.conf.js 檔案
引入
const webpack = require(‘webpack‘)
在項目根目錄下的build 中可以找到webpack.base.conf.js 檔案,對檔案中的內容進行以下兩項操作:
在module.exports之前插入代碼
// define the different HOST between development and production environmentvar DEV_HOST = JSON.stringify(‘http://192.168.32.12:8080‘)var PUB_HOST = JSON.stringify(‘http://{部署伺服器ip和連接埠}‘)
在module.exports 中添加與entry、output、resolve等選項並列的plutins選項
plugins: [ new webpack.DefinePlugin({ HOST: process.env.NODE_ENV === ‘production‘ ? PUB_HOST : DEV_HOST })
2.3 配置main.js 檔案
import axios from ‘axios‘axios.defaults.baseURL = HOSTwindow.axios = axioswindow.HOST = HOST const bus = new Vue()window.bus = bus
3. 實現步驟二之封裝axios
3.1 建立http.js 檔案, static下邊建立 js 檔案夾
const apiMethods = { methods: { apiGet(url, data) { return new Promise((resolve, reject) => { axios.get(url, data).then((response) => { resolve(response.data) }, (response) => { reject(response) console.log(response) bus.$message({ message: ‘請求逾時,請檢查網路‘, type: ‘warning‘ }) }) }) }, apiPost(url, data) { return new Promise((resolve, reject) => { axios.post(url, data, { headers: { ‘Content-Type‘: ‘application/json‘ } }).then((response) => { resolve(response.data) }).catch((response) => { console.log(‘f‘, response) resolve(response) bus.$message({ message: ‘請求逾時,請檢查網路‘, type: ‘warning‘ }) }) }) } }}export default apiMethods
3.2 檔案引入
在需要發送ajax的請求檔案中引入http.js
import http from ‘../../../../static/js/http.js‘
並在該檔案的export default 末尾添加選項
mixins: [http]
3.3 方法調用
this.apiGet(‘/index.php/api/v1/goods/list‘, { params: { property_name: ‘秒殺‘ } }) .then((res) => { if(res.code == 0){ this.hotListDate = res.result; }else{ this.$message.error(res.message); } }, (err) => { console.log(err) });
post
this.apiPost(‘/index.php/api/v1/user/login‘, { mobile : this.form.phone, password : this.form.password }) .then((res) => { if(res.code == 0){ }else{ this.$message.error(res.message); } }, (err) => { console.log(err) });
Vue: axios 請求封裝及設定預設網域名稱首碼 (for Vue 2.0)