1.什么是跨域
首先!什么是跨域?跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是****浏览器施加的****安全限制。
所谓同源是指,域名,协议,端口号均相同。例如:
http://www.123.com/index.html 调用 http://www.123.com/server.php (非跨域)
http://www.123.com/index.html 调用 http://www.456.com/server.php (主域名不同:123/456,跨域)
http://abc.123.com/index.html 调用 http://def.123.com/server.php (子域名不同:abc/def,跨域)
http://www.123.com:8080/index.html 调用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)
http://www.123.com/index.html 调用 https://www.123.com/server.php (协议不同:http/https,跨域)
请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。
浏览器执行javascript脚本时,会检查这个脚本属于哪个页面,如果不是同源页面,就不会被执行。
2.跨域问题的出现
在前端vue2中请求数据:
<script>
import Myinfo from './components/Myinfo/Myinfo.vue'
import Mydetailinfo from './components/Mydetailinfo/Mydetailinfo.vue'
import axios from 'axios'
axios.defaults.withCredentials = true
export default {
name: 'App',
props: ['soncomp'],
data() {
return {
isshow: false,
sonvalue: '',
qqnum: '1233211234567'
}
},
methods: {
getData(myinfo) {
this.sonvalue = myinfo
},
getDataFromServe() {
// 本地启动vue2项目的地址为:http://localhost:8080/
// 此时我们会发现前端服务器地址和后端服务器地址端口号不同,属于跨域访问
axios.get('http://localhost:8000/article/articletag').then(
response => {console.log('ok',response.data);},
error => {console.log('error!'), error}
)
}
},
components: {
Myinfo,
Mydetailinfo
}
}
</script>
如上代码发出请求时会出现如下错误:
意思为:从来源’http://localhost:8080’访问’http://localhost:8000/article/articletag’的XMLHttpRequest已被CORS策略阻止:所请求的资源上没有’Access- control - allow - origin '标头。
3.如何解决跨域
- 让后端人员在
nginx
上配置代理,实现数据同源(弊端是配置之后任何人都可以从这台服务器要数据)。 jsonp
只能解决get
请求的跨域问题,对于post
、put
、delete
请求产生的跨域问题就没法解决- 配置代理服务器,使用
cli
配置代理服务器
具体可以参考官网链接
此时我们修改我们原来的代码:
<script>
import Myinfo from './components/Myinfo/Myinfo.vue'
import Mydetailinfo from './components/Mydetailinfo/Mydetailinfo.vue'
import axios from 'axios'
axios.defaults.withCredentials = true
export default {
name: 'App',
methods: {
getDataFromServe() {
// 端口号改为当前vue项目的服务器地址端口号
axios.get('http://localhost:8080/article/articletag').then(
response => {console.log('ok',response.data);},
error => {console.log('error!'), error}
)
}
}
}
</script>
在项目根目录的vue.config.js
中:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
devServer: {
proxy: 'http://localhost:8000'
},
// devServer: {
// proxy: {
// '/api': {
// target: '<url>',
// ws: true,
// changeOrigin: true
// },
// '/foo': {
// target: '<other_url>'
// }
// }
// },
transpileDependencies: true
})
修改配置文件时记得重启项目~!!!!!
此时我们成功请求到数据:
结束。