【问题标题】:Node.js request library -- post text/xml to body?Node.js 请求库——将文本/xml 发布到正文?
【发布时间】:2013-10-03 21:42:16
【问题描述】:

我正在尝试设置一个简单的 node.js 代理来将帖子传递给 Web 服务(本例中为 CSW)。

我在请求正文中发布 XML,并指定 text/xml。 -- 服务需要这些。

我在 req.rawBody var 中获得了原始 xml 文本,它工作正常,但是我似乎无法正确重新提交它。

我的方法如下:

app.post('/csw*', function(req, res){


  console.log("Making request to:"  + geobusOptions.host + "With query params: " + req.rawBody);


request.post(
    {url:'http://192.168.0.100/csw',
    body : req.rawBody,
    'Content-Type': 'text/xml'
    },
    function (error, response, body) {        
        if (!error && response.statusCode == 200) {
            console.log(body)
        }
    }
);
});

我只想在 POST 中提交一个字符串,使用内容类型 text/xml。然而,我似乎无法做到这一点!

我正在使用“请求”库@https://github.com/mikeal/request

编辑——哎呀!我忘了只添加标题...

这很好用:

request.post(
    {url:'http://192.168.0.100/csw',
    body : req.rawBody,
    headers: {'Content-Type': 'text/xml'}
    },
    function (error, response, body) {        
        if (!error && response.statusCode == 200) {
            console.log(body)
        }
    }
);

【问题讨论】:

标签: node.js express request


【解决方案1】:

好吧,我最终想通了,要重新发布 nodeJS 代理请求的正文,我有以下方法:

request.post(
    {url:'http://192.168.0.100/csw',
    body : req.rawBody,
    headers: {'Content-Type': 'text/xml'}
    },
    function (error, response, body) {        
        if (!error && response.statusCode == 200) {
            console.log(body)
        }
    }
);

我使用以下代码获取 rawbody:

app.use(function(req, res, next) {
  req.rawBody = '';
  req.setEncoding('utf8');

  req.on('data', function(chunk) { 
    req.rawBody += chunk;
  });

  req.on('end', function() {
    next();
  });
});

【讨论】:

  • 只是好奇,您建议使用什么库来解析也是 XML 的请求响应正文?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 2015-03-17
  • 2020-12-13
  • 1970-01-01
  • 2012-09-12
相关资源
最近更新 更多