【问题标题】:Post request body as XML string in node.js在 node.js 中将请求正文作为 XML 字符串发布
【发布时间】:2019-12-22 22:08:51
【问题描述】:

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

这是我发布 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
    });
}

如何编辑代码以在请求正文中发布 XML 字符串(xmlRequest)而不是 JSON(请求)。

【问题讨论】:

    标签: node.js xml fetch fetch-api


    【解决方案1】:

    在正文中发送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

    【讨论】:

    • 我完全按照上面的方式更改代码。但是,在运行服务器并在控制台console.log(req.body) 中打印请求正文后,它会打印 { } 空请求!!
    • 您询问如何将xml 发送到服务器,您就是这样做的。检查网络选项卡,看看您实际上是在发送 XML。为什么您的服务器不接受它,超出了这个问题的范围,我们无法通过给定的信息告诉您。您应该发布服务器代码,或者更好地为此创建一个不同的问题,我很乐意为您提供帮助。
    • 如果您的服务器无法处理它,为什么还要在XML 中发送它?如果req.body 为空,则表示您没有解析 XML。您应该实现或使用 XML 正文解析器...
    猜你喜欢
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    相关资源
    最近更新 更多