Home > Article > Web Front-end > How to configure a proxy using routing components in Node.js
With the development of front-end development, more and more applications need to communicate with back-end servers through API interfaces. But one problem developers face is how to bypass cross-origin restrictions, a mechanism introduced by browsers for security reasons to prevent cross-site attacks.
Proxy is a common way to solve cross-origin restrictions. By sending the browser's request to the proxy server, and the proxy server forwarding the request to the real interface address, we can bypass cross-origin restrictions and access the interface. In this article, we'll cover how to configure a proxy using the routing component in Node.js.
In Node.js, we have multiple options to configure the proxy. Taking Express as an example, the commonly used solutions are as follows:
In this article, we will introduce the first solution.
We need to install the http-proxy-middleware plug-in to implement the proxy function.
$ npm install http-proxy-middleware --save-dev
In Express, we can use the express.Router() method to create routing instances. We can configure a proxy for each routing instance.
const express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); const router = express.Router(); // 配置代理 router.use('/api', createProxyMiddleware({ target: 'http://www.example.com', changeOrigin: true })); app.use(router); // 启动服务器 const server = app.listen(3000, () => { const { address, port } = server.address(); console.log(`Listening on http://${address}:${port}`); });
The above code proxies requests with the routing address /api to the http://www.example.com address by configuring a route.
In createProxyMiddleware, we can configure multiple options to customize the proxy configuration. For example, we can use the pathRewrite option to rewrite the path to remove the /api prefix in the routing address to match the real interface address:
router.use('/api', createProxyMiddleware({ target: 'http://www.example.com', changeOrigin: true, pathRewrite: { '^/api': '' } }));
The above code will proxy / in the future path. The api prefix is removed.
In addition to configuring the proxy, we can also configure the interceptor to customize the proxy behavior. Interceptors are used to process requests and responses. For example, we can add header information before the request is initiated, or process the return value after the request response.
In http-proxy-middleware, we can configure the interceptor through onProxyReq and onProxyRes two options.
// router.use('/api', createProxyMiddleware({ target: 'http://www.example.com', changeOrigin: true, onProxyReq: (proxyReq, req, res) => { // 在请求发起前添加头部信息 proxyReq.setHeader('Authorization', 'Bearer ' + token); }, onProxyRes: (proxyRes, req, res) => { // 在响应返回后处理返回值 const data = proxyRes.body.toString('utf8'); const newData = JSON.parse(data).result; res.send(newData); } }));
In the above code, we added a header information named Authorization in onProxyReq and processed the return value in onProxyRes.
Through the above introduction, we have learned how to use the http-proxy-middleware plug-in to implement the routing proxy function, and we have also learned how to implement it through middleware. In addition, we also learned to configure interceptors to handle requests and responses.
Node.js provides many convenient tools to help us implement proxy functions, helping developers quickly build and deploy applications. I hope this article will help you to use proxies to solve cross-site communication problems in your back-end development work.
The above is the detailed content of How to configure a proxy using routing components in Node.js. For more information, please follow other related articles on the PHP Chinese website!