简体   繁体   English

Node.js + express 如何在请求正文中添加字符串?

[英]Node.js + express how to add string to the request body?

I have a reverse proxy that works fine:我有一个工作正常的反向代理:

app.post('/geoserver', function (req, res) {
    apiProxy.web(req, res, {target: serverOne});
});

The request has already a body as following:该请求已经有如下正文:

在此处输入图像描述

I need to add to the request body a string similar to this one:我需要在请求正文中添加一个类似于此的字符串:

'<Filter> .... </Filter>'

Before proxying to the serverOne .在代理到serverOne之前。

Tried with req.body = req.body.replace('</Query>','<Filter>.... </Filter></Query>') but body seems to be undefined.尝试使用req.body = req.body.replace('</Query>','<Filter>.... </Filter></Query>')但正文似乎未定义。

Any idea on how to solve this?关于如何解决这个问题的任何想法? Big thanks!非常感谢!

Look, anything can be changed into string by String conversion.看,任何东西都可以通过字符串转换变成字符串。 but here in this case you can use JSON.stringify(JSON.parse(*)), * can be any format for which you want to change the format, here JSON.parse() will format your text and JSON.stringify() will help you to make valid JSON format.但在这种情况下,您可以使用 JSON.stringify(JSON.parse(*)), * 可以是您要更改格式的任何格式,这里 JSON.parse() 将格式化您的文本和 Z0ECD11C1C1D7A28D7402F8(8BB3)将帮助您制作有效的 JSON 格式。

First of all, the body might be undefined if the request is failing, or incorrectly parsed.首先,如果请求失败或解析不正确,主体可能undefined

Try app.use(express.bodyParser()) .试试app.use(express.bodyParser()) It's better to use it on the whole app.最好在整个应用程序上使用它。

Sometimes, when express is failing, you might want to use connect.有时,当 express 失败时,您可能需要使用connect。

If you are using it, there might be some place for reverse engineering, and checking if the most simple request is reaching, since the screenshot you've provided is from the dev tools, right?如果您正在使用它,可能会有一些地方进行逆向工程,并检查是否达到了最简单的请求,因为您提供的屏幕截图来自开发工具,对吗? That means it might be only sent, but not received/incorrectly interpreted.这意味着它可能只被发送,但没有被接收/被错误解释。

As I found no solution , finally created a.Net handler that easily allows to modify the body content.由于我没有找到解决方案,最后创建了一个.Net 处理程序,可以轻松修改正文内容。

Accepting as solution for closing the question.接受作为结束问题的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM