Expressjs response as JSON and Xml

痴心易碎 提交于 2019-12-03 21:25:26

问题


What i am doing:: I am trying to generate json and xml output for a dataset from database

Express Code:: Here i am trying for JSON response

var express = require('express')
  , async = require('async')
  , http = require('http')
  , mysql = require('mysql'); 
  var xml = require('xml');

var app = express();

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    database: 'MyDatabase'
});

connection.connect();

// all environments
app.set('port', process.env.PORT || 3007);

app.use(express.static(__dirname + '/public/images'));

app.get('/Result/',function(request,response){
    var name_of_restaurants;

    async.series( [
        // Get the first table contents
        function ( callback ) {
            connection.query('SELECT * FROM mas_buf_type', function(err, rows, fields)
                {
                        console.log('Connection result error '+err);
                        name_of_restaurants = rows;
                        callback();
                });

 }

   // Send the response
], function ( error, results ) {


 response.json({'restaurants' : name_of_restaurants });



//response.set('Content-Type', 'text/xml');
//response.send(xml(name_of_restaurants));
} );

} );




http.createServer(app).listen(app.get('port'),function(){
        console.log('Express server listening on port'+app.get('port'));
});

My Output::

{
    "restaurants": [
        {
            "Buf_Type_Id": 1,
            "Buf_Type_Name": "Breakfast"
        },
        {
            "Buf_Type_Id": 2,
            "Buf_Type_Name": "Lunch"
        },
        {
            "Buf_Type_Id": 3,
            "Buf_Type_Name": "Dinner"
        }
    ]
}

Now instead of

 response.json({'restaurants' : name_of_restaurants });

I have added these lines to get XML output

response.set('Content-Type', 'text/xml');
response.send(xml(name_of_restaurants));

Output::

<Buf_Type_Id>1</Buf_Type_Id>
<Buf_Type_Id>2</Buf_Type_Id>
<Buf_Type_Id>3</Buf_Type_Id>

My QUESTION::

  • Clearly you can see both output are different and i cannot find second column in xml output
  • how to resolve this
  • what changes should i need to make

{EDIT}

var express = require('express')
  , async = require('async')
  , http = require('http')
  , mysql = require('mysql'); 
  var xml = require('xml');

var app = express();

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    database: 'findmybuffet'
});

connection.connect();

// all environments
app.set('port', process.env.PORT || 3007);

app.use(express.static(__dirname + '/public/images'));

app.get('/Result/',function(request,response){
    var name_of_restaurants;

    async.series( [
        // Get the first table contents
        function ( callback ) {
            connection.query('SELECT * FROM mas_buf_type', function(err, rows, fields)
                {
                        console.log('Connection result error '+err);
                        name_of_restaurants = rows;
                        callback();
                });

 }

   // Send the response
], function ( error, results ) {


 //response.json({'restaurants' : name_of_restaurants });

response.set('Content-Type', 'text/xml');
//response.send(xml(name_of_restaurants));

response.send(xml({restaurants:[
    name_of_restaurants.map(function(r){
        return [ 
            { Buf_Type_Id: r.Buf_Type_Id },
            { Buf_Type_Name: r.Buf_Type_Name },
        ]
    })
]}));


} );

} );


http.createServer(app).listen(app.get('port'),function(){
        console.log('Express server listening on port'+app.get('port'));
});

Output::

<restaurants>
    <0>
        <Buf_Type_Id>1</Buf_Type_Id>
        <Buf_Type_Name>Breakfast</Buf_Type_Name>
    </0>
</restaurants>

Also clearly we can see <0> getting generated .... which is not required ...how to remove this ?


回答1:


So I've looked around for a better object-to-XML mapper for you. I tried three before I found one that I liked (it's easy-to-use, and it makes sense for your application). Ditch the old one, and use object-to-xml instead:

var o2x = require('object-to-xml');

response.set('Content-Type', 'text/xml');
response.send(o2x({
    '?xml version="1.0" encoding="utf-8"?' : null,
    restaurants: {
        restaurant: name_of_restaurants
    }
}));



回答2:


Those <0> tags are there because you are embedding an array into 'restaurants'. Instead of that, try to name every restaurant as an object array:

...

response.send(xml({restaurants:[
    name_of_restaurants.map(function(r){
        return { restaurant_name? :
            [ 
                { Buf_Type_Id: r.Buf_Type_Id },
                { Buf_Type_Name: r.Buf_Type_Name }
            ]
    })
]}));

...



来源:https://stackoverflow.com/questions/21399572/expressjs-response-as-json-and-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!