简单易用的前端本地开发接口代理服务
Author: 图恩Category: 编程开发Views: 820Published: 2022-05-02 **Article**
---
### **Background**
During the interface integration phase in front-end development, we often encounter cross-origin (CORS) issues. Typically, local projects are launched using the `localhost` domain. While we can solve this by configuring the `host` parameter, we need to disable the host when accessing online pages. Additionally, we can configure proxies using the `dev-server` plugin of Webpack, but when working with multiple backend developers, we need to set up multiple proxies and virtual interface prefixes. Furthermore, after deployment, the proxy should not be used. Overall, the configuration process is cumbersome.
---
### **Objective**
To address the above issues, we aim to develop a simpler and more flexible interface proxy solution. Our goals are:
1. **Ease of use**: Minimal code addition to the frontend project.
2. **Environment isolation**: Proxy is only used in local development; no impact on production.
3. **Flexible configuration**: Support for differentiated configurations for different APIs and simultaneous integration with multiple backend developers.
---
### **Solution**
When using the `dev-server` plugin of Webpack, essentially we run a proxy service locally. Frontend requests are forwarded to this proxy service, which then forwards them to the actual backend API URL. The proxy service transmits the returned data back to the frontend.
Based on this principle, we independently develop a proxy service and run it locally, achieving the same proxy functionality as the `dev-server` plugin. In this solution, we introduce a more flexible configuration method by modifying the `config.json` file to simplify the configuration and enable on-the-fly adjustments.
---
### **Implementation**
#### **1. Creating a Node.js Project**
- **Step 1**: Create a Node.js project locally (requires Node.js environment, recommended version: 12+).
- **Project Name**: `api-proxy-server`
- **Note**: The source code of this proxy service is freely provided. Simply **like and follow** in the comments to request it, and leave your email for immediate delivery. The `README` file details the usage instructions for quick integration.
#### **2. Writing an Express Service**
- **Framework**: Express (or other frameworks like KOA, Egg.js).
- **Code Example**:
```js
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
```
- **CORS Configuration**:
```js
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, X-Requested-With');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTION');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('X-Powered-By', '3.2.1');
next();
});
```
- **Default Route**:
```js
app.get('/', (req, res) => {
res.send('Hello, Welcome use api proxy.');
});
```
- **Service Startup**:
```js
const port = 8080;
http.createServer(app).listen(port);
console.log(`http://127.0.0.1:${port} 服务已启动`);
```
---
#### **3. Writing Proxy Interface**
- **Route Configuration**: Define the proxy interface at `/api`.
- **Code Example**:
```js
const api = require('./routes/api');
app.post('/api', api);
```
- **Note**: The proxy interface is configured at `/api`, so the full URL for frontend access is `http://127.0.0.1:8080/api`. This interface is only accessible via `axios` due to being a `POST` request.
- **Configuration File** (`src/routes/api/config.json`):
```json
{
"baseUrl": "http://192.168.1.17",
"method": "POST",
"contentType": "json"
}
```
- **Dynamic Configuration**:
```js
const configPath = fspath.resolve(process.cwd(), './src/routes/api/config.json');
if (!fs.existsSync(configPath)) {
res.json({ code: '-1', msg: '接口配置文件不存在!' });
return;
}
const configStr = fs.readFileSync(configPath, { encoding: 'utf-8' });
let config = null;
try {
config = JSON.parse(configStr);
} catch (error) {
res.json({ code: '-1', msg: '接口配置文件格式有误,解析失败!' });
return;
}
let { baseUrl, method = 'POST', contentType = 'json', extra = [] } = config;
```
---
### **Frontend Integration**
- **Development Environment**: In the frontend project, set the base URL to the proxy service when in development.
- **Code Example**:
```js
let baseUrl = 'http://api.xyz.com'; // 线上接口域名
let data = { a: 1 };
let path = '/user/permision';
let url = baseUrl + path;
if (process.env.NODE_ENV === 'development') {
url = 'http://127.0.0.1:8080/api';
data = { path, params: data };
}
axios({ url, data })
```
- **Note**: Modify the `config.json` file and save it without restarting the service. If the computer is turned off and restarted, manual startup is required.
---
### **Conclusion**
This proxy service has been developed and can be integrated into frontend projects. For development environments, set the base URL to the proxy service, and the frontend will automatically use it. The service is fully functional and supports dynamic configuration for different APIs.
---
### **Additional Notes**
- **Source Code**: The source code of this proxy service is freely provided. Simply **like and follow** in the comments to request it, and leave your email for immediate delivery.
- **Usage Instructions**: The `README` file details how to use the service for quick integration.