Who says the front End doesn’t Need to understand -Nginx Reverse Proxy and load Balancing

Nginx load balancing has nothing to do with front-end load balancing.

Of course, it is good to make a popular science article for the front end to let everyone know more about one item. The article pulls to the back to see the author’s use scenario, for example, to talk about a host to let the product go check. Isn’t it a Webserver container and a reverse proxy?

This content is very hot, combined with the recent chat group always someone asked, I think there are a lot of people want to know about this knowledge, so here also popular science, commonly used proxy.

This article is widely loved by friends, indicating that it is helpful to many friends. In addition, many netizens have great opinions on the title of this article. The title of this article is for the title of the citation, which aims to emphasize that there is a more appropriate way to do the right thing, and does not prevent us from learning more knowledge

Method 1. Use the HTTP-server module for proxy

Those of you familiar with NodeJS should know that there is a very nice and powerful tool module called HTTP-Server, which is a little rocket that can help you soar to the sky. It can be used as follows:

Nodejs needs to be installed first. I won’t repeat it here.

Installing global modules

 npm install http-server -g
Copy the code

Then go to the HTML resource directory where you need to run the display

http-server -P http://www.your-backend.com/api
Copy the code

http://www.your-backend.com/api is the address of your back – end reverse proxy interface, which you need to change to your own.

Then you can use http://localhost:8080 for access (if port 8080 is not occupied, you can specify another port if it is occupied), super easy? You can query the official document http-server for more parameters.

The highlight of this tool is zero configuration, anytime anywhere to start for small friends to go to check, mobile debugging is not three seconds, do you have to bother to write a nginx configuration?

2. Use WebPack to configure the agent

Webpack is a powerful tool for the front end, and in addition to helping you package and start up the debug server, it’s worth checking out the functionality of the agent. Use the official website documentation address

Simplest way:

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': 'http://localhost:3000'}}};Copy the code

The above configuration acts as a proxy by automatically forwarding/API access requests to http://localhost:3000.

If you need to remove the API prefix from your rule, you can override the address.

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: {'^/api' : ' '}}}}};Copy the code

You may also encounter HTTPS security issues that trigger unauthenticated certificate errors, which you can simply add Secure: false to handle

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'https://other-server.example.com',
        secure: false}}}};Copy the code

Sometimes you don’t want to delegate all requests. An agent can be bypassed based on the return value of a function. Within functions you can access the request body, response body, and proxy options. False or path must be returned to skip the proxy request. For example, you want to serve an HTML page for browser requests, but keep proxies for API requests. Here’s what you can do:

proxy: {
  "/api": {
    target: "http://localhost:3000",
    bypass: function(req, res, proxyOptions) {
      if (req.headers.accept.indexOf("html") !== -1) {
        console.log("Skipping proxy for browser request.");
        return "/index.html"; }}}}Copy the code

Multiple path proxy

proxy: [{
  context: ["/auth"."/api"],
  target: "http://localhost:3000",}]Copy the code

In short, WebPack provides a variety of flexible ways to meet your requirements most of the time.

This method is most suitable for projects that have enabled the Webpack project to start automatically with project startup

Tip 3: Use the Node-HTTP-proxy module of NodeJS

Node-http-proxy provides a programmatically structured proxy environment that can handle complex hackers if you have special requirements such as session, cookie bound domain processing to other domains, or content conversion processing.

Such as adding a special request header;

var http = require('http'),
    httpProxy = require('http-proxy');
 
var proxy = httpProxy.createProxyServer({});

 
proxy.on('proxyReq'.function(proxyReq, req, res, options) {
  proxyReq.setHeader('X-Special-Proxy-Header'.'foobar');
});

var server = http.createServer(function(req, res) {
  // You can define here your custom logic to handle the request
  // and then proxy the request.
  proxy.web(req, res, {
    target: 'http://127.0.0.1:5060'
  });
});

console.log("listening on port 5050")
server.listen(5050);
Copy the code

See the official documentation for more information

Use the framework’s own proxy, such as angular proxy.

Angular proxy is basically the same as WebPack. You need a configuration file like proxy.conf.json for my open source project Typerx

{
    "/api": {
        "target": "http://localhost:5400/"."secure": false
    },
    "/user": {
        "target": "http://localhost:5400/"."secure": false
    },
    "/uploads": {
        "target": "http://localhost:5400/"."secure": false}}Copy the code

After the configuration is complete, specify proxy.conf.json with the proxy-config parameter to invoke the proxy configuration

 ng serve --proxy-config proxy.conf.json
Copy the code

More ways, if you look at more ways is it the same as Webpack, in fact it is Webpack?

This way is the correct use of posture after engineering

Tip 5: This is not actually a proxy, but it can also solve your cross-domain problems.

open -n /Applications/Google\ Chrome.app/ --args --disable-web-security --user-data-dir=/Users/your/path/
Copy the code

Another option is of course Nginx

You can continue to understand him who says front-end doesn’t need to understand -Nginx reverse proxy with load balancing