vue-cli、webpack等打包工具在浏览器调试环境下的跨域解决配置方法

前端开发 浏览器调试环境下,需要配置localhost往实际后台接口的代理:以下是用不同工具时的配置方案:

vue项目vue-cli脚手架:vue.config.js

module.exports = {
  publicPath: './',
  outputDir: 'dist',
  assetsDir: 'static',
  devServer: {
    open: true, // 自动打开浏览器
    host: '0.0.0.0',
    port: 8080,
    hot: true,
    disableHostCheck: true, //  解决host报错问题
    proxy: {
      //配置跨域
      '/api': {
        //解:当请求 /api 时就会代理到 http://srv.cs.cmmurl.cn:28080/api 请求
        target: 'http://srv.cs.cmmurl.cn:28080/',
        changeOrigin: true, // 允许跨域
        secure: true, //允许https请求
      }
    }
  }
}

使用webpack构建的项目:webpack.dev.config.js


const merge = require('webpack-merge');
const webpack = require('webpack');
const commonConfig = require('./webpack.common.config');

module.exports = merge(commonConfig, {
    mode: 'development',
    devServer: {
        port: 9000,
        hot: true,
        host: 'localhost',
        compress: true,
        open: true,
        historyApiFallback: {
            index: '/my-invoice/index.html'
        },
        publicPath: '/my-invoice/',
        proxy: {    //配置跨域
            '/invoice': { //这里的值根据与后端同志约定的值来定,这里的含义是发送请求至包含/invoice的url时,转发到目标代理服务器https://my-invoice.cs.cmmurl.cn:28443/invoice进行数据请求
                target: 'https://my-invoice.cs.cmmurl.cn:28443/',
                changeOrigin: true,
                secure: false,
            },
        },
        disableHostCheck: true,
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('development'),
        }),
    ],
});


版权声明:本文为llq886原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。