Vue配置方式
解决ajax请求跨域问题
发送请求的方式
1、xhr new XMLHttpRequest() xhr.open() xhr.send()
2、jQuery $.get $.post
3、axios,promise风格,主流
4、fetch,兼容性稍差
以上都是对于xhr的封装,fetch是与xhr平级的,promise风格。
安装axios
npm install axios
跨域问题是浏览器拦截,服务器获取了请求,且也发送了数据
解决跨域问题的方法
1、cors
2、jsonp 只能解决get请求,很巧妙
3、配置一个代理服务器—(1、nginx 2、vue-cli)
配置代理:
方式一:
vue-cli官方文档中的devServer.proxy
在项目文件中的vue.config.js中添加
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave:false,//关闭语法检查
devServer:{
proxy:'http://localhost:3001'
},
})
缺点只能配置一个代理、不能确定是否转发请求。
方式二:
devServer:{
proxy:{
//请求前缀
'/api':{
target:'<url>',
//使用正则表达式匹配去替换掉请求中的转发头
pathRewrite:{'^/atguigu':''},
//websocket的支持
ws:true,
//用于控制请求头中host值
changeOrigin:true
},
'/demo':{
target:'<url>',
//使用正则表达式匹配去替换掉请求中的转发头
pathRewrite:{'^/demo':''},
//websocket的支持
ws:true,
//用于控制请求头中host值
changeOrigin:true
}
}
}
- 本文链接:https://archer-lan.github.io/2023/11/20/Vue%E9%85%8D%E7%BD%AE%E4%BB%A3%E7%90%86/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。