Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement the front-end local development interface proxy service by Node

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the relevant knowledge of "how to implement the front-end local development interface proxy service by Node". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Background

In the interface joint debugging phase of front-end development, we often encounter cross-domain problems, because the local localhost domain name is usually used to start the project. Of course, we can solve this problem by configuring host, but when we need to access the online page, we must close host. We can also configure Proxy through webpack plug-in dev-server, but sometimes we need to jointly tune interfaces with multiple server R & D, so we need to configure multiple Proxy, set multiple virtual interface prefixes, and consider how to avoid proxies online after publishing. On the whole, the configuration work is more troublesome.

target

In view of the above background, we need a more simple and flexible interface proxy scheme, our goal is:

Easy to access, only need to add a small amount of code to the front-end project

Environment isolation, using agents only for the local development environment, no images online, and no need to modify the code when releasing

Flexible configuration: it can be configured differently for different interfaces, and multiple server R & D can be jointly tuned at the same time.

Scheme

When we use the plug-in dev-server of webpack, we essentially run a proxy service locally. The network requests sent by the front-end page actually request the proxy service, and then the proxy service forwards it to the actual interface URL. Finally, the proxy service transmits the data returned by the interface to the front-end page.

According to this principle, we build a proxy service from the bank and run it locally to achieve the same proxy process as the dev-server plug-in, but we will introduce a more flexible configuration method in this scheme, that is, by modifying the config.json configuration file to achieve more simplified configuration and flexible features.

Implement and create a NodeJS project

First create a NodeJS project locally (you need to install the NodeJS environment, version recommendation 12 +), named api-proxy-server, with brief steps.

Warm Tip: this article's agent service project source code, the author provides free of charge! Just like + follow, you can leave a message in the comment area and leave your email address, which I will send as soon as I see it. The project source code README file describes in detail how to use it, which is convenient for you to quickly access.

Write Express services

Our proxy service is developed using the Express framework (you need to install dependencies), and you can also use other frameworks, such as KOA, Egg.js, etc., according to your personal habits.

First import related dependencies in the project master file:

Const express = require ('express'); const http = require (' http'); const bodyParser = require ('body-parser'); const app = express ()

Then use bodyParser to parse the request data:

App.use (bodyParser.urlencoded ({extended: false})); app.use (bodyParser.json ())

The next key step is to allow cross-domain access. We need to allow access to all domain names and requests. The specific settings are as follows:

App.all ('*', (req, res, next) = > {res.header ('Access-Control-Allow-Origin', req.headers.origin); res.header (' Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, Xmuri RequestedMuth`); res.header (' Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTION'); res.header (' Access-Control-Allow-Credentials', 'true') Res.header ('Xmuri PowerBuilder,' 3.2.1'); next ();})

Then we write a default route for the service (which can also be understood as an interface. For the front end, the route provided by the server can be regarded as an interface). The default route is defined as a GET request, which is convenient for us to access directly in the browser to verify whether the service has started successfully.

Express mounts routes in the following ways:

App.get ('/', (req, res) = > {res.send ('Hello, Welcome use api proxy.');})

Finally, let's write the code to start the service, as follows:

Const port = 808010 http.createServer (app) .requests (port); console.log (`http://127.0.0.1:${port} service has been started`)

After writing the code according to the above steps, start the service and access http://127.0.0.1:8080 in the browser. If you see the browser showing "Hello, Welcome use api proxy." Speaking of which, the service started successfully.

On how to start the service, the author's approach is to configure the startup script dev in package.json, and then run npm run dev, or you can start the service through the pm2 process guard plug-in (you need to install dependencies), which has the advantage of ensuring that the service will not stop when the program reports an error.

The startup script is configured as follows:

"scripts": {"start": "pm2 start. / src/server.js", "stop": "pm2 stop. / src/server.js", "dev": "node. / src/server.js"}, write proxy interface

In the above steps, we can start the proxy service and write a default GET route (interface). Next, let's implement the core of this article, writing an interface of type POST to proxy front-end interface requests.

In order to facilitate subsequent maintenance and expansion, we write the source code of the proxy interface into a separate file, the directory is src/routes/api, the file name is index.js, and then import and mount the route in the main file as follows:

Const api = require ('. / routes/api'); / / .app.post ('/ api', api)

Note: the routing of the proxy interface is defined as / api, so the full path to invoke this service in the front-end project is http://127.0.0.1:8080/api, and this interface can only be accessed through axios because it is of type POST and does not support browser access authentication.

We open the src/routes/api/index.js file to write the specific code, and first export a basic routing function:

Const axios = require ("axios"); const qs = require ("qs"); const fs = require ("fs"); const fspath = require ("path"); module.exports = (req, res) = > {/ /.}

In this function, we deal with the front-end request, first getting the parameters from the request body:

Const {path, params} = req.body

Where path specifies which server interface path to access, and params is the actual input parameter to be passed through to the server.

Then under the src/routes/api/ directory, we create an interface profile, config.json, which maintains the default server interface domain name or IP address, as well as the default request method and data type. The specific definition is as follows:

Attribute name describes the http://192.168.1.17method request method of the default address of the sample baseUrl server interface. The default is POSTGET / POSTcontentType data type, and the default is jsonform / json

Continue to write code to read the config.json configuration file, as follows:

/ / read the interface configuration file const configPath = fspath.resolve (process.cwd (),'. / src/routes/api/config.json'); if (! fs.existsSync (configPath)) {res.json ({code:'- 1 configuration, msg: 'interface configuration file does not exist!' }); return;} const configStr = fs.readFileSync (configPath, {encoding: 'utf-8'}); let config = null;try {config = JSON.parse (configStr);} catch (error) {res.json ({code:'-1 configuration, msg: 'API configuration file format error, parsing failed!' }); return;} / / get the default configuration of the interface let {baseUrl, method='POST', contentType='json', extra= []} = config

After writing the code, we have got the real server interface address, request type and data type, and then we can send the request through axios, but this does not support the differentiation of individual requests. For example, some APIs need to be debugged with other server R & D, that is, baseUrl is different, some APIs request type is GET, and some APIs request data type is application/x-www-form-urlencoded. So we need a mechanism to configure the differentiated interface. We continue to rewrite the config.json file and add the extra array. In this array, we put a set of objects to define the differentiated properties of individual interfaces, as follows:

Attribute name description example path interface path (required), need differentiated configuration of interface / user/permisionbaseUrl server interface address (optional) http://192.168.1.16method request method (optional) GET / POSTcontentType data type (optional) form / json

With the above configuration, we can traverse the extra array. If the path requested by the current API is in it, the request needs to be sent according to the differentiated configuration, as shown below:

/ / get additional interface configuration if (extra.length > 0) {const extraCfg = extra.find (item = > item.path = path); if (extraCfg) {baseUrl = extraCfg.baseUrl | | baseUrl; method = extraCfg.method | | method; contentType = extraCfg.contentType | | contentType;}}

Finally, we use axios to send the request to the actual server interface address, and then send the returned data to the front page. The code is as follows:

Const url = baseUrl + path;const headers = {}; if (contentType = 'form') {headers [' Content-Type'] = 'application/x-www-form-urlencoded';} axios ({method, url, headers, timeout: 3000, data: contentType =' form'? Qs.stringify (params): params}) .then (result = > {res.json (result.data); Log.api (url, params, result.data);}) .catch (error = > {res.json ({code:'- 1 error, msg: 'network error'}); Log.api (url, params, 'network error');})

The Log in the code is used to record logs, so it is convenient for us to track the operation of the agent service. The specific implementation can be viewed in the source code of this project.

At this point, our proxy service has been developed, and by running the service, we can access and use it in the front-end project. * * Note: * * after we modify the config.json file, we can save it without restarting the service. If the computer shuts down and restarts, the agent service needs to be started manually.

Front-end project access

At the place where the front-end project encapsulates the axios request, determine that if it is the local development environment, point the URL to the service and simply wrap the input parameters. Because we only do the interface proxy for the local environment, there is no need to modify when publishing the project, and the released version will still call the actual server interface.

Code example:

Let baseUrl = 'http://api.xyz.com'; / / the domain name of the online interface let data = {a: 1} / / the interface input parameter let path =' / user/permision'; / / the actual interface path let url = baseUrl + path; / / the complete interface urlif of the request (process.env.NODE_ENV = = 'development') {url =' http://127.0.0.1:8080/api'; Data = {path, params: data}} / / send request axios ({url, data}) "how to implement the front-end local development interface proxy service by Node" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report