zoukankan      html  css  js  c++  java
  • vue-cli构建的项目中axios的请求方式及跨域处理

    vue-cli axios请求方式以及跨域处理

    • 安装axios
      cnpm install axios --save

    • 在要使用axios的文件中引入axios

        1.main.js文件 :import axios from 'axois'
        2.要发送请求的文件:import axios from 'axois'
      
    • 在config/index.js文件设置代理

         dev: { 	
            proxyTable: {// 输入/api 让其去访问http://localhost:3000/api
              '/api':{   
                  target:'http://localhost:3000'//设置调用的接口域名和端口号 ( 设置代理目标)
      
              },
              '/api/*':{
                target:'http://localhost:3000'
              },
        	changeOrigin: true,
        	 pathRewrite: { //路径重写 
                    '^/api': '/' //这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://localhost:3002/user/add',直接写‘/api/goods/add’即可
                }  
      
        	}
         	试一下,跨域成功,但是这知识开发环境(dev)中解决了跨域问题,生产环境中正真部署到服务器上如果是非同源还是存在跨域问题。
      

    axios请求方式

    Get请求

    	// 向具有指定id的用户发出请求
    	axios.get('/user?id=1001')
    	  .then(function (response) {
    	    console.log(response.data);
    	  }).catch(function (error) {
    	    console.log(error);
    	  });
    	// 也可以通过 params 对象传递参数
    	axios.get('/user', {
    	    params: {
    	      id: 1001
    	    }
    	  }).then(function (response) {//请求成功回调函数
    	    console.log(response);
    	  }).catch(function (error) {//请求失败时的回调函数
    	    console.log(error);
    	  });
    

    post请求

    	axios.post('/user', {
    	    userId: '10001'  //注意post请求发送参数的方式和get请求方式是有区别的
    	  }).then(function (response) {
    	    console.log(response);
    	  }).catch(function (error) {
    	    console.log(error);
    	  });
  • 相关阅读:
    交流课件
    ARC127F ±AB
    CF1566F xor-quiz
    JOISC 2016 Day 1 棋盘游戏
    dev分支和release是什么
    drf 笔记
    drf 序列化的写法 总结
    Linux系统编程
    C/C++ 网络编程
    C++提高编程
  • 原文地址:https://www.cnblogs.com/pangwl/p/8099412.html
Copyright © 2011-2022 走看看