1. 安装 http-proxy-middleware
npm install http-proxy-middleware
#顺便安装一下 axios ,不用也可以,用fetch也一样。
npm install axios
2. src目录下创建一个 setupProxy.js文件
里面的'api'代表target的域名url代理后的url
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: 'https://eyesight.news.qq.com/',
changeOrigin: true,
pathRewrite: {
'^/api': '',
}
})
);
app.use(
'/apc',
createProxyMiddleware({
target: 'https://api.inews.qq.com/',
changeOrigin: true,
pathRewrite: {
'^/apc': '',
}
})
);
};
3. 发送axious请求
getData() {
// 开启loading特效
const instance = axios.create({
baseURL: '/api/sars/toheros',
timeout: 3000,
headers: { 'Content-Type': 'application/json' }
});
return new Promise((resolve, reject) => {
console.log('开始调用')
instance.get('')
.then((response) => {
console.log(response)
resolve(response);
})
.catch((e) => {
reject(e)
console.log(e)
})
})
}