raju
raju

Reputation: 6946

res.send XML is giving empty Document in Express

I am trying simple api which return sml response :

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const libxmljs = require("libxmljs");

const PORT = process.env.PORT || 5000;

const app = express()

app.use(cors());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json());

app.get('/', (req, res) => {
    res.send({ "message": "success" });
});

app.get('/api', (req, res) => {
    var libxmljs = require("libxmljs");
    var xml =  '<?xml version="1.0" encoding="UTF-8"?>' +
               '<root>' +
                   '<child foo="bar">' +
                       '<grandchild baz="fizbuzz">grandchild content</grandchild>' +
                   '</child>' +
                   '<sibling>with content!</sibling>' +
               '</root>';

    var xmlDoc = libxmljs.parseXml(xml);

    // xpath queries
    var gchild = xmlDoc.get('//grandchild');

    console.log(gchild.text());  // prints "grandchild content"

    var children = xmlDoc.root().childNodes();
    var child = children[0];

    console.log(child.attr('foo').value()); // prints "bar"

    res.set('Content-Type', 'text/xml');
    res.send(xmlDoc);
});

app.listen(PORT, () => {
    console.log(`App running on PORT ${PORT}`)
});

here everthing is showing as expected in node console, but in the APi response i am not getting XML, I am getting this error:

This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.

Please help

Upvotes: 0

Views: 624

Answers (1)

BENARD Patrick
BENARD Patrick

Reputation: 31005

I see that you copy the code from github repo.

You're sending as response the xml object, not the string....

Instead of

res.send(xmlDoc);

do

res.send(xml);

Upvotes: 1

Related Questions