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);
});
得到接口数据。