zoukankan      html  css  js  c++  java
  • vue 中使用axios 发起跨域请求

    最近在项目中使用到axios组件的跨域请求,经过一番研究后,特此记录。

    1、安装axios

    $  npm install axios -S

    2、配置axios

    在项目的目录结构的 src 文件夹下创建api文件夹,并在此文件夹下创建AxiosConfig.js文件,用于配置axios。

    AxiosConfig.js 详细内容如下:

    import axios from 'axios';
    import store from 'storejs';
    let http = axios.create({
        baseURL: 'http://xxxxxxx/', //后台服务地址 
        withCredentials: true,
        headers: {
          
        },
        transformRequest: [function (data,headers) {
          if (headers['Content-type'] === 'multipart/form-data') {
            return data;
          } else {
            return JSON.stringify(data);
          }
          // let newData = '';
          // for (let k in data) {
          //   if (data.hasOwnProperty(k) === true) {
          //     newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
          //   }
          // }
          // return newData;
        }]
      });
      
      function apiAxios(method, url, params, token, response) {
        http({
          method: method,
          url: url,
          headers:{
            'Content-Type': 'application/json;charset=utf-8',
            'token': token
          },
          data: method === 'POST' || method === 'PUT' ? params : null,
          params: method === 'GET' || method === 'DELETE' ? params : null,
        }).then(function (res) {
          response(res);
        }).catch(function (err) {
          response(err);
        })
      }
      
      export default {
        get: function (url, params, token, response) {
          return apiAxios('GET', url, params, token, response)
        },
        post: function (url, params, token, response) {
          return apiAxios('POST', url, params, token, response)
        },
        put: function (url, params, token, response) {
          return apiAxios('PUT', url, params, token, response)
        },
        delete: function (url, params, token, response) {
          return apiAxios('DELETE', url, params, token, response)
        }
      }

    这里的配置了POST、GET、PUT、DELETE方法。并且自动将JSON格式数据转为URL拼接的方式

    同时配置了跨域,不需要的话将 withCredentials 设置为 false 即可

    此处由于业务原因,配置请求的 headers 在创建的时候配置,并添加 用于验证的 token 信息。

    3、使用axios

    首先在main.js中引入方法

    import Api from './api/AxiosConfig';
    Vue.prototype.$api=Api;

    配置完成以后,在需要的地方直接调用即可

    this.$api.post('/请求地址', {
                     "参数名":"参数值"
                    }, token, response => {
                        if (response.status >= 200 && response.status < 300) {
                           console.log(response.data);\请求成功,response为成功信息参数
                        } else {
                           console.log(response.message);\请求失败,response为失败信息
                        }
                    });

  • 相关阅读:
    三种负载均衡 Nginx、Dubbo、Ribbon 区别
    Docker基础学习
    主从复制报错2061:Authentication plugin 'caching_sha2_password' reported error:Authentication require secure connection
    LRU、LFU算法区别
    CAP理论原理
    Mysql安装服务到Window服务列表
    从零开始掌握 HAProxy 负载均衡器,详细!!
    一举拿下Nginx
    Nginx 负载均衡配置误区
    Linux自动化技巧
  • 原文地址:https://www.cnblogs.com/guoxiangyue/p/12455384.html
Copyright © 2011-2022 走看看