Post 请求正文作为 node.js 中的 XML 字符串

Post request body as XML string in node.js

我正在尝试 post XML 字符串而不是 JSON 对象到 node.js 服务器使用 fetch API。

这是我的代码,post JSON 对象:

handleSubmit = async e => {

    e.preventDefault();
    var request = JSON.stringify({
        drug: this.state.drug,
        disease: this.state.disease,
        type: this.state.type    
    });
    var xmlRequest = js2xmlparser.parse("request", request);

    const response = await fetch('/api/submit', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: request
    });

    const body = await response.text();

    this.setState({
        responseToPost: body
    });
}

如何在请求正文中将代码编辑为 post XML string(xmlRequest) 而不是 JSON(请求)。

在正文中发送 xmlRequest 而不是 request。同时将 Content-Type 更改为 text/xmlapplication/xml

const request = {
    drug: this.state.drug,
    disease: this.state.disease,
    type: this.state.type    
};

const xmlRequest = js2xmlparser.parse('request', request);

const response = await fetch('/api/submit', {
    method: 'POST',
    headers: {
        'Content-Type': 'text/xml'
    },
    body: xmlRequest
});

js2xmlparser 将一个对象作为第二个参数,不要使用 JSON.stringify.