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

我有一个简单的代码,为特定的路线提供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?

您可以使用npm上提供的任何数量的XML库。 这是一个使用简单的“ xml ”库的例子:

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

查看模块的文档,了解如何将JavaScript对象转换为XML。 如果你需要以特定的XML格式返回的东西,当然你需要做更多的工作。