Skip to main content

Backend interface proxy problem

When the front-end project and the back-end project are not deployed on the same server or on different ports of the same server, the front-end project cannot access the back-end interface. In this case, a reverse proxy is needed to proxy the front-end request to the address where the back-end project is deployed.

Preface

At present, mainstream front-end and back-end projects are designed in a separated way, with the front-end responsible for rendering pages and the back-end responsible for providing data interfaces. react19 seems to be playing with a "very new thing", server-side rendering, which can directly embed sql statements in the front-end project to operate the database. How to say it, php is back, and it is back in a new identity!

Let’s get back to our topic: how to deal with the problem of backend interface proxy after nginx deploys the front-end project.

Identify the problem

In the development stage, most scaffolds have built-in http-proxy-middleware , and cross-domain access to backend interfaces can be completed through simple proxy configuration, for example:

http-proxy-middleware official examples
import * as express from 'express';
import {
createProxyMiddleware,
Filter,
Options,
RequestHandler,
} from 'http-proxy-middleware';

const app = express();

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

app.listen(3000);

// proxy and keep the same base path "/api"
// http://127.0.0.1:3000/api/foo/bar -> http://www.example.org/api/foo/bar

However, the proxy of http-proxy-middleware is only used in the development stage. It will not be packaged into the project during packaging, and is only used as a development dependency.

So how can we achieve the same effect by deploying the project through nginx?

solution

Add one more location, taking the proxy api as an example:

nginx.conf 1
location /api {
#Set the proxy target (backend interface address)
proxy_pass https://api.eaveluo.com;
}

The above configuration forwards all requests with /api as baseURL in the front-end project to the back-end project https://api.eaveluo.com/api.

However, this has a problem for some requirements. If the back-end address does not have the /api prefix, it cannot be accessed normally. In this case, the following configuration can be used:

nginx.conf 2
location /api/ {
#Set the proxy target (backend interface address)
proxy_pass https://api.eaveluo.com/;
}

Note the subtle difference between the two snippets of code above. Compared to nginx.conf 1, nginx.conf 2 has an additional / after /api, so that all requests with /api as baseURL can be forwarded to the backend project https://api.eaveluo.com without adding the /api prefix.

Loading Comments...