一尘不染

如何使用ExpressJS在XML中进行响应?

node.js

我有一个简单的代码,可为特定路由提供JSON响应。这是我当前的代码:

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

var app = express();

var connection = mysql.createConnection({
    host: 'localhost',
    user: '****',
    password: "****",
    database: 'restaurants'
});

connection.connect();

// all environments
app.set('port', process.env.PORT || 1235);
app.use(express.static(__dirname + '/public/images'));


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

    async.series( [
        // Get the first table contents
        function ( callback ) {
            connection.query('SELECT * FROM restaurants ORDER BY restaurantRATING', 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
    });
} );

} );



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

如何使XML响应等效于上述JSON?


阅读 271

收藏
2020-07-07

共1个答案

一尘不染

您可以使用npm上可用的任何数量的XML库。这是使用简单命名的“ xml ”库的示例:

var xml = require('xml');

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

有关如何将JavaScript对象转换为XML的描述,请参见模块的文档。当然,如果您需要以特定的XML格式返回的内容,则还有更多工作要做。

2020-07-07