Cross-domain problems arise: The same-origin policy, a security mechanism used by browsers to isolate potentially malicious files, restricts interaction between resources that are not same-origin. Webpack uses Proxy to solve cross-domain problems. Webpack-dev-server based, suitable for development phase only. The configuration is as follows:

// ./webpack.config.js const path = require('path') module.exports = { // ... {contentBase: path.join(__dirname, 'dist'), compress: true, port: 9000, // Construct proxy proxy: {'/ API ': { target: 'https://api.github.com' } } // ... }}

The property is an object, and each rule in the object is the rule matching of a proxy. The name of the property is the prefix of the request path to be proxied, which is usually set to/API for identification. The value is the proxy matching rule of the object, which is as follows:

  • Target: Represents the target address to which the agent is going
  • Pathrewrite: By default, our /api-hy is also written to the RUL, so if you want to delete it, you can use Pathrewrite
  • Secure: By default does not accept forwarding to HTTPS servers, set to false if you wish to support it
  • ChangeOrigin: This is the host address in headers indicating whether to update the agent after the request

Listing uses the HTTP proxy middleware HTTP-Proxy-Middleware to forward requests to other servers. At development stage, the local address is

Http://loaclhost:3000, the browser sends a request to the wiper prefixed with the/API identifier, but the server simply forwards the request to another server:

const express = require('express');
const proxy = require('http-proxy-middleware');

const app = express();

app.use('/api', proxy({target: 'http://www.example.org', changeOrigin: true}));
app.listen(3000);

// http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar

During development, webpack-dev-server automatically starts a local development server, so our application runs on a separate localhost port during development, and the back-end server runs on a different address

Therefore, in the development stage, due to the same origin policy of the browser, cross-domain resource requests will occur when local access is performed. Setting Webpack Proxy to realize the proxy request is equivalent to adding a proxy between the browser and the server. When local sends a request, the server will accept the situation, and will forward the request to the target server, the target server after return data, among the data back to the browser, the server and when the data back to the server, they both are homologous, does not cross domain problems.

There is no cross-domain resource problem between servers.