Vue axjx 跨域请求

跨域请求

1.配置代理(方式一)

Vue代理服务器是一种用于支持Vue应用程序的服务器,它可以帮助开发人员更轻松地实现跨域请求。它可以帮助开发人员更轻松地实现跨域请求,并且可以提供更多的安全性和灵活性。Vue代理服务器可以帮助开发人员更轻松地实现跨域请求,并且可以提供更多的安全性和灵活性。它可以帮助开发人员更轻松地实现跨域请求,并且可以提供更多的安全性和灵活性。

1.安装

npm i axios

2.引入axios

import axios from 'axios'

3.配置代理服务器
在这里插入图片描述

注意配置的代理服务器的端口号3000 为你要请请求的服务器的端口号。

// 开启代理服务器
  devServer:{
    
    
    proxy:"http://localhost:3000"
  }

4.发送请求

注意:axios发送的请求是本地的端口,但是要带请求服务器的地址

在这里插入图片描述

 handsend(){
    
    
       axios.get('http://localhost:8080/index').then(
      response=>{
    
    
       console.log(response.data)
        },
        error=>{
    
    

        }
       )
    }

在这里插入图片描述

1.配置代理(方式二)

用于配置多个代理,pathRewrite重写路径。

 devServer:{
    
    
    proxy:{
    
    
      '/api':{
    
     //以api开头的请求
        target:"http://localhost:3000", //代理目标的基础路径
        pathRewrite:{
    
       //重写路径
          '^/api':''
        },
        ws:true
      },
      '/api2':{
    
    
        target:"http://localhost:3001",
        pathRewrite:{
    
    
          '^/api':''
        },
        ws:true
      }
    }
  }

注意在请求时要加上api的前缀。

扫描二维码关注公众号,回复: 16842493 查看本文章
 handsend(){
    
    
       axios.get('http://localhost:8080/api/index').then(
      response=>{
    
    
       console.log(response.data)
        },
        error=>{
    
    

        }
       )
    }

猜你喜欢

转载自blog.csdn.net/qq_48164590/article/details/129053635