在vue-cli脚手架搭建的项目中使用axios前端代理
目录
在vue-cli脚手架搭建的项目中使用axios前端代理
有些项目中可能会在前端使用代理请求数据,写一篇文章来说一下对于前端axios在vue项目中怎么使用
首先你需要安装axios依赖,请输入一下命令:
$ npm install axios –save (因为是在前端代码中使用所以安装的时候使用–save)
接着在build目录下的webpack.dev.conf.js中请求数据的代码如下:
devServer: {
before(app){
app.get('/api/getDiscList', function (req, res) {
const url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg'
axios.get(url, {
headers: {
referer: 'https://c.y.qq.com/',
host: 'c.y.qq.com'
},
params: req.query
}).then((response) => {
res.json(response.data)
}).catch((e) => {
console.log(e)
})
})
},
clientLogLevel: 'warning',
在devServer中写入以上代码之前你需要引入axios
之后在你要请求数据得页面中使用axios请求webpack.dev.conf.js自己写的接口(上面代码中标红的)
代码如下:
export function getDiscList() {
const url = '/api/getDiscList'
const data = Object.assign({}, commonParams, {
platform: 'yqq',
hostUin: 0,
sin: 0,
ein: 29,
needNewCode: 0,
sortId: 5,
categoryId: 10000000,
rnd: Math.random(),
format: 'json'
})
return axios.get(url, {
params: data
}).then((res) => {
return Promise.resolve(res.data)
})
}
这样就能欺骗服务器,使用代理请求到数据了1
写到这里,希望能够帮到你们