vue.config.js配置文件
在使用vue-cli3創建項目後,因爲webpack的配置均被隱藏了,當你需要覆蓋原有的配置時,則需要在項目的根目錄下,新建vue.config.js文件,來配置新的配置。
const url = require('url');
const queryString = require('querystring');
const path = require('path');
const axios = require('axios');
const { newList } = require('./src/mock/data.json');
module.exports = {
// 所有 webpack-dev-server 的選項都支持。
// nodejs express的小型web服務器
// devServer的before在服務內部的所有其他中間件之前,
//提供執行自定義中間件的功能。 這可以用來配置自定義處理程序。
devServer: {
before(app) {
app.get('/getNewsList', (request, response) => {
const oUrl = url.parse(request.url)
const oQuery = queryString.parse(oUrl.query)
const types = oQuery.types || "history"
const result = newList.filter((itm) => {
return itm.key === types
})
response.json({
code: 1,
result
})
})
}
}
}
proxy 實現跨域
配置多個代理
有時候我們使用webpack在本地啓動服務器的時候,由於我們使用的訪問的域名是 http://localhost:8081 這樣的,但是我們服務端的接口是其他的,
那麼就存在域名或端口號跨域的情況下,但是很幸運的是 devServer有一個叫proxy配置項,可以通過該配置來解決跨域的問題,那是因爲 dev-server 使用了 http-proxy-middleware 包。
現在我們只需要在devServer中的proxy的配置就可以了:
如下配置:
proxy: {
'/api': {
target: 'http://localhost:3000', // 目標接口的域名
// secure: true, // https 的時候 使用該參數
changeOrigin: true, // 是否跨域
pathRewrite: {
'^/api' : '' // 重寫路徑, 去掉接口地址中的api字符串
},
"/foo": {
target: "http://localhost:8080", // 本地模擬數據服務器
changeOrigin: true,
pathRewrite: {
"^/foo": "" // 去掉接口地址中的foo字符串
}
}
}
}
因此所有的配置如下:
module.exports = {
devServer: {
// contentBase: path.join(__dirname, "dist"),
headers: {
'X-foo': '112233'
},
hot: true, //熱更新替換,更新頁面
port: '8081', // 端口號
host: 'localhost',//指定要使用的主機IP。默認情況下這是localhost。
open: true, //自動啓動瀏覽器
compress: true, //爲所服務的一切啓用gzip壓縮
proxy: {
'/api': {
target: 'http://news.baidu.com', // 目標接口的域名
// secure: true, // https 的時候 使用該參數
changeOrigin: true, // 是否跨域
pathRewrite: {
'^/api' : '' // 重寫路徑
}
}
}
}
}
然後我們在組件裏面編寫如下代碼:
import axios from 'axios';
axios.get('/api/widget?ajax=json&id=ad').then(res => {
console.log(res);
});
得到接口數據。