axios请求

Axios

1. 安装axios

npm i axios

//在需要请求接口的组件中引入 axios
import axios from 'axios'

2. 语法格式

created(){
    //解决跨域问题时,如果在路径中写代理名,代理名也会成为路径
    
    axios.get|post('请求路径',{
        params:{
            键:值,
            键:值
        }
    }).then(res=>{
        
    }).catch(err=>{
        
    })
}

3. 跨域问题

跨域: 协议,域名,端口号有一个不一致就会产生跨域

1) 跨域说明
eg:
服务端: http://localhost:8090/index
客户端: http://localhost:8081/
       上面端口号不一致 => 跨域

报错: Access to XMLHttpRequest at 'http://localhost:8091/index' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
2) 解决跨域
Axios解决跨域方式: 写代理
设置代理: 
	找到vue.config.js配置文件
3) vue.config.js 写代理,解决跨域
module.exports={
  devServer:{
    
    port:9090,	// 设置新端口号
      
    // 设置代理
    proxy:{
      //直接写代理
      '代理名':{
        target:'要代理的服务器地址'
      }
      '/index':{
        target:'http://localhost:8090'
      },

      // 如果需要自定义代理名,需要重写路径
      '/api':{
        target:'代理名',
        pathRewrite:{
          '^/api':''
        }
      }
      '/api':{
        target:'http://localhost:8090',
        pathRewrite:{
          "^/api":''
        }
      }
    }
  }
}
posted @   又又儿  阅读(417)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示