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
      }
    }
  }