iview-cli 項目、iView admin 跨域問題解決方案


在build 目錄的 webpack.dev.config.js 目錄中

module.exports = merge(webpackBaseConfig, {
    devtool: '#source-map',
    output: {
        publicPath: '/dist/',
        filename: '[name].js',
        chunkFilename: '[name].chunk.js'
    },
    plugins: [
        new ExtractTextPlugin({
            filename: '[name].css',
            allChunks: true
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendors',
            filename: 'vendors.js'
        }),
        new HtmlWebpackPlugin({
            filename: '../index.html',
            template: './src/template/index.ejs',
            inject: false
        })
    ],
    //設置跨域代理
    devServer: {
        historyApiFallback: true,
        hot: true,
        inline: true,
        stats: { colors: true },
        proxy: {
            //匹配代理的url
            '/api': {
            // 目標服務器地址
              target: 'http://127.0.0.1:8081',
              //路徑重寫
              pathRewrite: {'^/api' : '/api'},
              changeOrigin: true
            }
         }
    }

請求時

//引入axios
import axios from 'axios';


//請求方法,根據實際情況使用
axios.get('/api/user').then((res) => {
                //res 為成功回調的響應
                    console.log(res);
                });    

配置后則可以將請求轉發到

http://127.0.0.1:8081

此處以本機啟動服務器為例
請根據具體情況自行更改


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM