带有 REST 和参数的 NodeJS 代理
NodeJS proxy with REST and parameters
让 NodeJS 服务器充当私人服务器的网关。一个简单的 REST 端点工作如下。但是,我正在寻找一种解决方案,该解决方案也将通过 Axios 可能发送的任何参数。
Axios 调用代理服务器示例
return axios
.post(http://proxy.server + "/company/add_company", { address:"123 main", phone:"555-1234" })
代理服务器
const caller = async (response, rest, params) => {
try {
params = JSON.parse(params);
const result = await axios.post('http://10.0.0.0'+ rest, { params } );
res.status(200).json({
success: true,
result: result.data
})
} catch (err) {
res.status(500).json({
success: false,
err
})
}
}
app.all("/", (request, response) => {
let params = request.body // <= not working
let rest = request.url; // <= working example => /users/235
caller(response, rest, params);
});
您需要使用解析器中间件从客户端接收post数据,数据将存储在request.body中。
示例:
const express = require('express');
const app = express();
// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: false }))
// parse application/json
app.use(express.json())
这是对我有用的解决方案。
const httpProxy = require('http-proxy');
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/', createProxyMiddleware({ target: 'http://10.0.0.0' , changeOrigin: true }));
app.listen(5000);
让 NodeJS 服务器充当私人服务器的网关。一个简单的 REST 端点工作如下。但是,我正在寻找一种解决方案,该解决方案也将通过 Axios 可能发送的任何参数。
Axios 调用代理服务器示例
return axios
.post(http://proxy.server + "/company/add_company", { address:"123 main", phone:"555-1234" })
代理服务器
const caller = async (response, rest, params) => {
try {
params = JSON.parse(params);
const result = await axios.post('http://10.0.0.0'+ rest, { params } );
res.status(200).json({
success: true,
result: result.data
})
} catch (err) {
res.status(500).json({
success: false,
err
})
}
}
app.all("/", (request, response) => {
let params = request.body // <= not working
let rest = request.url; // <= working example => /users/235
caller(response, rest, params);
});
您需要使用解析器中间件从客户端接收post数据,数据将存储在request.body中。 示例:
const express = require('express');
const app = express();
// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: false }))
// parse application/json
app.use(express.json())
这是对我有用的解决方案。
const httpProxy = require('http-proxy');
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/', createProxyMiddleware({ target: 'http://10.0.0.0' , changeOrigin: true }));
app.listen(5000);