猿问

怎么在express中使用axios?

在express配置中已经使用了中间件http-proxy-middleware并且配置了转发
app.use('/api',proxy({
target:'http://x.x.x.x.',
changeOrigin:true,
pathRewrite:{
'^/api':'/'
}
}));
而在app.get方法中使用axios的时候会报错:
app.get('/index/test',function(req,res){
axios.get('/api/index/getdata.html?page=1')//这里如果写成http://x.x.x.x/index/getdata.html?page=1就不会报错
.then(result=>{
console.log(result);
returnres.send('test');
})
});
output
(node:12952)UnhandledPromiseRejectionWarning:Unhandledpromiserejection(rejectionid:2):Error:Requestfailedwithstatuscode404
(node:12952)[DEP0018]DeprecationWarning:Unhandledpromiserejectionsaredeprecated.Inthefuture,promiserejectionsthatarenothandledwillterminatetheNode.jsprocesswithanon-zeroexitcode.
其中我想要使用/api,不知道怎么实现?
慕桂英4014372
浏览 1726回答 2
2回答

精慕HU

调整代理proxyTable:{'/':{target:'http://localhost:8888/api',changeOrigin:true,pathRewrite:{'^/':'/'}},},在你的vue文件中引入axios,然后使用,如下:importaxiosfrom'axios'exportdefault{data(){return{titleCate:[],}},mounted(){this.init();},methods:{init(){axios.get('/titlecate').then((response)=>{this.titleCate=response.data;});}}}以上
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答