How to configure a proxy using routing components in Node.js

PHPz
Release: 2023-04-17 16:55:28
Original
994 people have browsed it

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.

Options to configure the proxy

In Node.js, we have multiple options to configure the proxy. Taking Express as an example, the commonly used solutions are as follows:

  1. Use http-proxy-middleware plug-in
  2. Customize middleware to implement
  3. Use Node. The http module that comes with js

In this article, we will introduce the first solution.

1. Install the plug-in

We need to install the http-proxy-middleware plug-in to implement the proxy function.

$ npm install http-proxy-middleware --save-dev
Copy after login

2. Configure routing and proxy

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}`);
});
Copy after login

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': '' } 
}));
Copy after login

The above code will proxy / in the future path. The api prefix is ​​removed.

3. Configure the interceptor

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);
   }
}));
Copy after login

In the above code, we added a header information named Authorization in onProxyReq and processed the return value in onProxyRes.

Summary

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!