在Vue中配置跨域可以通过修改配置文件或者使用插件来实现。下面分别介绍两种方法:
- 修改配置文件
在Vue的config文件夹下的index.js中,可以找到如下代码:
module.expor<em>ts</em> = { dev: { // ... }, // ... }
讯享网
在其中添加如下代码:
讯享网module.expor<em>ts</em> = { dev: { // ... proxyTable: { '/api': { target: 'http://localhost:3000', // 接口的域名 changeOrigin: true, // 如果接口<em>跨域</em>,需要进行这个参数<em>配置</em> pathRewrite: { '^/api': '' // 将/api替换为'' } } } }, // ... } 其中,proxyTable表示代理表;/api表示需要代理的接口路径;target表示接口的域名;changeOrigin表示是否跨域;pathRewrite表示路径重写。
然后在发送请求时,将接口路径改为/api/即可。

例如:
this.$http.get('/api/userinfo').then((response) => { console.log(response.data) })
- 使用插件
可以使用axios或者vue-resource等插件来发送跨域请求。以axios为例,可以在main.js中添加如下代码:
讯享网import axios from 'axios' <em>Vue</em>.prototype.$http = axios.create({ baseURL: 'http://localhost:3000', // 接口的域名 timeout: 5000, // 请求超时时间 withCredentials: true, // 允许携带cookie crossDomain: true // 允许<em>跨域</em> }) 然后在组件中使用:
this.$http.get('/userinfo').then((response) => { console.log(response.data) }) 其中,baseURL表示接口的域名;timeout表示请求超时时间;withCredentials和crossDomain表示允许携带cookie和允许跨域。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/139155.html