Nodejs Wechat official account development, can not automatically reply to the question of the message

can get the message sent by the user to the official account, but failed to send the xml data of the reply through res.end (), that is, the user cannot receive the message replied in the background. The official account shows a failure. If you uncomment a line of res.setHeader in your code, there will be an error of Can"t set headers after they are sent. ?

req.on("end", function(){
    util.parseXMLAsync(postData)
    .then(result => {
        console.log(result)
        var now = new Date().getTime()
        if(result.MsgType === "event"){
            if(result.Event === "subscribe"){
                result.Content = "~"
            }
        }
        // res.setHeader("Content-Type", "text/xml")
        var response = `<xml>
                        <ToUserName>< ![CDATA[${result.FromUserName}] ]></ToUserName>
                        <FromUserName>< ![CDATA[${result.ToUserName}] ]></FromUserName>
                        <CreateTime>${now}</CreateTime>
                        <MsgType>< ![CDATA[text] ]></MsgType>
                        <Content>< ![CDATA[${result.Content}] ]></Content>
                    </xml>`
        res.end(response)
    })
})

result the result of converting the received xml to json

Mar.07,2021

platitudes, node asynchronous programming, modify header, please use writeheader


I have tried to use writeHead, as mentioned in the previous answer, but I have not encountered any problems

const http = require('http');

let server = http.createServer(function (req, res) {
    let result = {
        FromUserName: 'weixin',
        ToUserName: 'segment',
        Content: 'xxxx'
    }, now = Date.now();

    res.setHeader('Content-Type', 'text/xml')
    var response = `<xml>
            <ToUserName><![CDATA[${result.FromUserName}]]></ToUserName>
            <FromUserName><![CDATA[${result.ToUserName}]]></FromUserName>
            <CreateTime>${now}</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[${result.Content}]]></Content>
        </xml>`
    res.end(response)
}).listen(3001);

Thank you for your answers. The problem has been solved. The problem of
is actually due to the fact that the xml string response contains spaces, that is, and ]] . If you remove all these spaces, you can reply normally.
however, this xml string is copied from the official document, that is, the xml string in the official document contains spaces.
on the question of res.end (response) , the xml string has actually been sent to the Wechat server, but due to the existence of spaces, the Wechat server thinks that this is not a correct reply, so it will make an error.

Menu