axios 使用
1
| npm install --save axios vue-axios
|
1 2 3 4 5 6 7
| import App from './App.vue' import * as Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios'
const app = Vue.createApp(App) app.use(VueAxios, axios)
|
1 2 3 4 5 6 7 8 9 10 11
| <script> import axios from 'axios'; export default { data (){ info: "" } mounted(){ axios.get("http://www.chinanonfiction.com/feed/").then(*response* *=>* { this.info = *response;*}).catch(err => {console.log(err);}) } </script>
|
CORS ERROR处理
问题场景
想在前端直接访问内容源网站的rss(http://www.chinanonfiction.com/feed/)。
但直接通过axios请求,会出现CORS的报错。
1 2
| axios.get("http://www.chinanonfiction.com/feed/").then(*response* *=>* { this.info = *response;*}).catch(err => {console.log(err);})
|

关于CORS引发原因的进一步解释可以参考基于vue-cli3/cli4解决前端使用axios跨域问题 。核心原因是浏览器的同源策略导致的。可以通过自建前端代理,避开直接请求调用。
解决方式
通过Vue的代理配置,避开浏览器硬性的同源策略。
定义将访问同源的http://localhots:8080/chinanonfiction/feed
代理转发为 http://www.chinanonfiction.com/feed/
- 在组件代码里使用代理的方式进行访问。
也就是访问http://localhots:8080/chinanonfiction/feed
1 2
| axios.get("/chinanonfiction/feed/").then(*response* *=>* { this.info = *response;*}).catch(err => {console.log(err);})
|
- 在vue.config.js增加代理配置,并重写路径。
也就是将http://localhots:8080/chinanonfiction/feed
代理转发为 http://www.chinanonfiction.com/chinanonfiction/feed
并改写为http://www.chinanonfiction.com/feed
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| module.exports = { devServer: { proxy: { '/chinanonfiction': { target: 'http://www.chinanonfiction.com', changeOrigin: true, ws: true, pathRewrite: { '^/chinanonfiction': '', } } } } }
|
- 对于多目标的请求可以通过增加对应的代理配置进行相应的访问。
Reference