Vue 跨越问题解决 No ‘Access"/>
Vue 跨越问题解决 No ‘Access
一、问题
Access to XMLHttpRequest at 'http://xxx/wx_pn/wx_code_ticket' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
二、解决方法
- 项目根目录下创建 vue.config.js
module.exports = {devServer: {open: true,host: 'localhost',port: 项目运行端口,https: false,hotOnly: false,proxy: {// 配置跨域'/api': {target: 'http://xxx',//后端接口地址ws: true,changOrigin: true,pathRewrite: {'^/api': ''}}},}}
- 配置main.js
import Vue from 'vue'
import axios from 'axios'
...Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'...
- 使用方式
方式一
// 微信公众号请求
import axios from 'axios'
// 超时时间
axios.defaults.timeout = 10 * 1000
// 跨域请求允许保存cookie
axios.defaults.withCredentials = truelet base = '/aaa'// 获取ticket
export const wx_code_ticket = () => {return axios({url:`${base}/bbb`,method:'GET',})
}
<script>
import {wx_code_ticket} from '@/api/wx_pn'
export default {name:'Code',data() {return {img_base64:'',}},beforeMount() {this.getCode()},methods:{getCode:()=>{return new Promise(()=>{console.log(wx_code_ticket)wx_code_ticket().then(resp=>{console.log(resp)})})}}
}
</script>
方式二
```js
<script>
export default {name:'Code',data() {return {img_base64:'',}},beforeMount() {this.$axios({url:`/aaa/bbb`,method:'GET',}).then(resp=>{console.log(resp)})},
}
</script>
参考:
.html
(原理)
更多推荐
Vue 跨越问题解决 No ‘Access
发布评论