vue使用Ajax跨域访问后端数据
1、什么是跨域
跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实施的安全限制。
无法跨域是浏览器对于用户安全的考虑。
2、Vue如何解决跨域跨域
1、porxy代理:
在项目文件夹根目录创建vue-config.js文件(以下为代码)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | module.exports={ lintOnSave:false, devServer:{ port:8081, proxy: { '/api': { target:"http://localhost:8080/", //设置你调用的接口域名和端口号 changeOrigin: true, //这里表示是否实现跨域 true为实现 pathRewrite: { // 以api开头的 "^/api":''这里理解成用‘/api’代替target里面的地址,后面组件中我们调接口时直接用api代替 比如我要调用'http://192.168.0.112:8080/student/add',直接写‘/api/student/add’即可 } } } } } |
在main.js中导入已安装好的axios:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import axios from 'axios' import qs from 'qs' const headers = { 'Content-Type': 'application/x-www-form-urlencoded' } //注册提交 export const register = async (user,pwd) => { // 如果是Get提交,参数放在params属性中,而且不需要进行转换 let response = await axios({ headers, method:"post", //以什么方法提交 url:"/api/project/register", //这里写要跳转serlvet地址 user,pwd }) }) return response; } |