网站建设的培训心得群推广
利用vue的脚手架巧妙的解决ajax跨域的问题
1 我们首先利用springboot服务搭建
注意这里引出了跨域[CORS ]的问题:
Access to XMLHttpRequest at 'http://localhost:5000/getUserInfo' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
请求http的同源策略:1 2 3 点必须保持一致。
http://localhost:5000/getUserInfo
1、协议名 http
2、主机名 localhost
3、端口号 5000
违背了同源策略就会造成跨域问题。这里引出了配置代理的解决方案:
2 配置代理服务器 - 借助vue cli 开启代理服务器
Vue CLI官网—配置参考—devServer.proxy:配置参考 | Vue CLI
如何开启代理服务器?借助vue cli 开启代理服务器:
如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。
devServer.proxy 可以是一个指向开发环境 API 服务器的字符串:
module.exports = {devServer: {proxy: 'http://localhost:4000'}
}
这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:4000。
但是如果我们在public文件夹中存在数据的话:
有一个请求顺序的问题:先找自己public文件夹的资源,如果没有在去服务器中查询。public文件夹就相当于8080服务器的根路径。public文件夹里有的东西都算是8080中有的。
<template><btn/>
</template><script>
import Btn from "@/components/Btn";export default {name: 'App',components: {Btn}
}
</script><style>
</style>
<template><div><button @click="get">请求数据</button></div>
</template><script>
import axios from 'axios'export default {name: `Btn`,methods: {get() {axios.get('http://localhost:8080/hello.txt').then(response => {console.log(response.data)},error => {console.log(error.message)})}}
}
</script><style>
</style>
const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,lintOnSave: false, // 关闭语法检查devServer: {proxy: 'http://localhost:5000'}
})
但是,以上方式不够灵活的控制走不走代理服务器,且不能够配置多个代理。基于此提出了如下解决方案:
如上问题,pathRewrite: {'^/inspur': ''},
改变来源请求的服务http:
changeOrigin: true
/*** changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000* changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080* changeOrigin默认值为true*/
1.优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
2.缺点:配置略微繁琐,请求资源时必须加前缀。
const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,lintOnSave: false, // 关闭语法检查devServer: {proxy: {'/inspur': { // 请求前缀,若想走代理就在http加一个 /apitarget: 'http://localhost:5000',pathRewrite: {'^/inspur': ''},ws: true, // 用于支持websocketchangeOrigin: true/*** changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000* changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080* changeOrigin默认值为true*/}}}
})