美文网首页
vue 解决跨域问题,设置本地代理

vue 解决跨域问题,设置本地代理

作者: symY_Y | 来源:发表于2019-04-19 09:55 被阅读0次

    创建request.js

    import axios from "axios";
    import qs from "qs";   // 数据序列化处理
    //添加请求拦截器
    axios.interceptors.request.use(
      config => {
        if (config.method === 'post') {
          config.data = qs.stringify(config.data)
        }
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
    //添加响应拦截器
    axios.interceptors.response.use(
      response => {
        return response;
      },
      error => {
        return Promise.resolve(error.response);
      }
    );
    
    axios.defaults.baseURL = "https://baidu.com"; //接口地址(在本地测试的时候把这句注释掉)
    axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    axios.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest";
    axios.defaults.timeout = 10000;
    
    function checkStatus(response) {
      return new Promise((resolve, reject) => {
        if (
          response &&
          (response.status === 200 ||
            response.status === 304 ||
            response.status === 400)
        ) {
          resolve(response.data);
        } else {
          reject({
            state: "0",
            message: "网络异常"
          });
        }
      });
    }
    export default {
      post(url, params) {  
        return axios({
          method: "post",
          url,
          data:params
        }).then(response => {
          return checkStatus(response);
        });
      },
      get(url, params) {
        //params = qs.stringify(params);
        return axios({
          method: "get",
          url,
          params
        }).then(response => {
          return checkStatus(response);
        });
      }
    };
    

    main.js

    import Vue from 'vue'
    import App from './App'
    // 引入element-ui
    import ElementUi from 'element-ui'
    
    import http from './assets/js/request'     //axios封装
    Vue.prototype.$http = http  
    
    import router from './router'
    Vue.use(ElementUi)
    
    new Vue({
      el: '#app',
      router,
      components: { App },
      template: '<App/>'
    })
    

    config/index.js

    module.exports = {
      dev: {
        // Paths
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {     // 本地代理要添加proxyTable,当然在打包上传服务器的时候,要注释掉(仅限解决本地跨域测试)
         '/':{
            target:'https://baidu.com',   // 代理地址
            changeOrigin:true,
            secure:false,
            pathRewrite:{
              '^/': ''
          }
          }
        },
    
        // Various Dev Server settings
        host: 'localhost', // can be overwritten by process.env.HOST
        port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
        autoOpenBrowser: false,
        errorOverlay: true,
        notifyOnErrors: true,
        poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
    
        // Use Eslint Loader?
        // If true, your code will be linted during bundling and
        // linting errors and warnings will be shown in the console.
        useEslint: true,
        // If true, eslint errors and warnings will also be shown in the error overlay
        // in the browser.
        showEslintErrorsInOverlay: false,
    
        /**
         * Source Maps
         */
    
        // https://webpack.js.org/configuration/devtool/#development
        devtool: 'cheap-module-eval-source-map',
    
        // If you have problems debugging vue-files in devtools,
        // set this to false - it *may* help
        // https://vue-loader.vuejs.org/en/options.html#cachebusting
        cacheBusting: true,
    
        cssSourceMap: true
      },
    
      build: {
        // Template for index.html
        index: path.resolve(__dirname, '../dist/index.html'),
    
        // Paths
        assetsRoot: path.resolve(__dirname, '../dist'),
        assetsSubDirectory: 'static',
        assetsPublicPath: './',
    
        /**
         * Source Maps
         */
    
        productionSourceMap: false,
        // https://webpack.js.org/configuration/devtool/#production
        devtool: '#source-map',
    
        // Gzip off by default as many popular static hosts such as
        // Surge or Netlify already gzip all static assets for you.
        // Before setting to `true`, make sure to:
        // npm install --save-dev compression-webpack-plugin
        productionGzip: false,
        productionGzipExtensions: ['js', 'css'],
    
        // Run the build command with an extra argument to
        // View the bundle analyzer report after build finishes:
        // `npm run build --report`
        // Set to `true` or `false` to always turn it on or off
        bundleAnalyzerReport: process.env.npm_config_report
      }
    }
    

    这个只适用于解决本地接口跨域,需要设置代理的问题,顺带axios封装

    相关文章

      网友评论

          本文标题:vue 解决跨域问题,设置本地代理

          本文链接:https://www.haomeiwen.com/subject/fgatgqtx.html