Cross-domain issues are a perennial problem in real development, and there are three solutions available from the Webpack perspective. No more talking. Get straight to the business

The proxy agent

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
  mode: 'development',
  devServer: {
    port: 3000,
    hot: true,
    open: true,
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    proxy: {
      '/api': {
        target: 'http://localhost:8888',
        pathRewrite: { '^/api': '' },
      },
    },
  },
  entry: './src/index.js',
  output: {
    filename: '[name][hash:8].js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader',
      },
    ],
  },

  resolve: {
    extensions: ['.jsx', '.mjs', '.js', '.json'],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
    }),
    new CleanWebpackPlugin(),
  ],
}
Copy the code

In the configuration above, all client “/ API” requests are proxyed to “http://localhost:8888” and replaced with “/ API” by pathRewrite.

Tips:

  • Multiple proxy targets can use context: [];
  • Hide the host header, changeOrigin: true;
  • Requests to root are not brokered by default, devServer.index option is specified as false value “” if necessary

devServer mock

Devserver. before intercepts all requests and the front end simulates the server’s return

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
  mode: 'development',
  devServer: {
    port: 3000,
    hot: true,
    open: true,
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    before(app) {
      app.get('/api/user', function(req, res) {
        res.json({text: 'aibfk'})
        res.end()
      })
    }
  },
  entry: './src/index.js',
  output: {
    filename: '[name][hash:8].js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader',
      },
    ],
  },

  resolve: {
    extensions: ['.jsx', '.mjs', '.js', '.json'],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
    }),
    new CleanWebpackPlugin(),
  ],
}
Copy the code

Before is executed before all middleware, and the parameter app is equivalent to express’s app

The server performs Webpack

The server takes webpack configuration, compilers and executes. At this time, the front-end and server are deployed on the same server, and the port is the same as the server port. Webpack no longer cares about devServer

To implement server-side webpack, use webpack-dev-middleware

$ yarn add webpack-dev-middleware -D
Copy the code

server.js

const express = require('express')
const webpack = require('webpack')
const devMiddleWare = require('webpack-dev-middleware')

const app = express()

const config = require('./webpack.config.js')
const compiler = webpack(config)

app.use(devMiddleWare(compiler))

app.get('/user', (req, res) => {
  res.json({name: 'user', age: 2000})
  res.end()
})
app.listen(8888)
console.log('server running 8888');
Copy the code

Then start the service, http://localhost:8888 can access the front-end application, and there is no cross-domain problem, which is equivalent to bypass the cross-domain problem of the front and back end

In addition to Webpack, there are many solutions to cross domain methods, such as Nginx/Docker intermediate proxy, JSONP, CORS, etc., interested can discuss together!!