@vue/cli
跨域
由于浏览器同源策略,凡是请求URL的协议、域名、端口三者之间任意一个与当前页面URL不同即为跨域。
种类
- 域名/IP不同
- 端口不同
- 协议不同,http和https
方法
开发环境
在项目根目录下创建vue.config.js
配置文件
module.exports = {
devServer: {
open: true, // 自动打开浏览器
host: 'localhost',
port: 8080,
https: false,
//以上的ip和端口是我们本机的;下面为需要跨域的
proxy: {
// 配置跨域
'/api': {
target: 'http://localhost:8081/', // 后端接口地址
ws: true,
changOrigin: true, // 允许跨域
pathRewrite: {
// '^/api': '' // 请求路径重定向,/api/xxx => /xxx
}
}
}
}
}
测试
<template>
<div>{{ user }}</div>
</template>
<script>
export default {
data(){
return {
user: null
}
},
created() {
var url = '/api/user/';
this.axios.get(url)
.then(res => {
this.user = res.data;
console.log(this.user)
})
}
}
</script>
<style>
</style>
生产环境
NGINX
- 第一种:修改前端配置,使用代理proxy_pass。
- 第二种:修改后端配置,response添加Access-Control-Allow-Origin响应头信息。