如何在节点中正确提交XML发布请求?

时间:2019-11-03 11:54:29

标签: javascript node.js xml post

我已经编写了以下代码来提交发布请求。服务器需要XML的请求。我不断收到消息无法使用内容类型的回复 OPERTAION_FAILED 。我遵循了API文档中提供的确切xml格式。你能帮我解决我做错了吗?

var request = require('request');
var crypto = require('crypto');
var xml = require('xml');
var express = require("express");
var app = express();
var utctime = new Date().toISOString()

var login = [SENSITIVE DATA];
var password = [SENSITIVE DATA];
var requestId = [SENSITIVE DATA];
var ownTaxNumber = [SENSITIVE DATA];
var searchedTaxNumber = [SENSITIVE DATA];
var signingKey = [SENSITIVE DATA];
var softwareId = [SENSITIVE DATA];

var hash = crypto.createHash('sha512');
data = hash.update(password, 'utf-8');
var hashPassword = data.digest('hex').toUpperCase();
var hash = crypto.createHash('sha512');
data = hash.update(requestId + utctime + signingKey, 'utf-8');
var requestSignature = data.digest('hex').toUpperCase();

var reqbody = '';
reqbody = reqbody + '<?xml version="1.0" encoding="UTF-8"?>';
reqbody = reqbody + '<QueryTaxpayerRequest xmlns="http://example.com/OSA/1.0/api">';
reqbody = reqbody + '<header>';
reqbody = reqbody + '<requestId>' + requestId + '</requestId>';
reqbody = reqbody + '<timestamp>' + utctime + '</timestamp>';
reqbody = reqbody + '<requestVersion>1.1</requestVersion>';
reqbody = reqbody + '<headerVersion>1.0</headerVersion>';
reqbody = reqbody + '</header>';
reqbody = reqbody + '<user>';
reqbody = reqbody + '<login>' + login + '</login>';
reqbody = reqbody + '<passwordHash>' + hashPassword + '</passwordHash>';
reqbody = reqbody + '<taxNumber>' + ownTaxNumber + '</taxNumber>';
reqbody = reqbody + '<requestSignature>' + requestSignature + '</requestSignature>';
reqbody = reqbody + '</user>';
reqbody = reqbody + '<software>';
reqbody = reqbody + '<softwareId>' + softwareId + '</softwareId>';
reqbody = reqbody + '</software>';
reqbody = reqbody + '<taxNumber>' + searchedTaxNumber + '</taxNumber>';
reqbody = reqbody + '</QueryTaxpayerRequest>';

console.log(reqbody);

request.post('https://example.com/invoiceService/queryTaxpayer', function (error, response, body) {
    response.headers['content-type'] = 'application/xml';
    response.body = xml(reqbody);
    if(error){
        console.log("Something went wrong!")
        console.log(error);
        console.log(body);
    } else{
        console.log(body);
        console.log(response.statusCode);
        console.log(error);
    }
});

即使我犯了一个愚蠢的错误,也请对我好。这是我在Node中的第一个项目。 :)

1 个答案:

答案 0 :(得分:1)

您需要将数据和标头作为请求的一部分而不是在响应中传递。

request.post({
  headers: { 'Content-Type': 'application/xml' },
  url: link,
  body: reqbody,
}, function(error, response, body){
  console.log(body);
});

您也不需要对XML请求正文进行双重编码-您自己(可能很危险)对XML进行编码,因此无需调用xml(reqbody) ...