0%

vue3中axios使用以及CORS ERROR处理

axios 使用

1
npm install --save axios vue-axios
  • 在main.js里import
1
2
3
4
5
6
7
import App from './App.vue'
import * as Vue from 'vue' // in Vue 3
import axios from 'axios'
import VueAxios from 'vue-axios'

const app = Vue.createApp(App)
app.use(VueAxios, axios)
  • 在components里调用
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_error

关于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',// 你要请求的后端接口ip+port或者网站域名
changeOrigin: true,// 允许跨域,在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
ws: true,// 开启webSocket
pathRewrite: {
'^/chinanonfiction': '',// 替换成target中的地址
}
}
}
}
}
  • 对于多目标的请求可以通过增加对应的代理配置进行相应的访问。

Reference