node.js 如何使用 ExpressJS 以 XML 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21398279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I respond in XML using ExpressJS?
提问by Devrath
I have a simple code that gives a JSON response for a specific route. Here's my current code:
我有一个简单的代码,可以为特定路由提供 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'));
});
How can I make an XML response equivalent to the JSON above?
如何使 XML 响应与上面的 JSON 等效?
回答by Ethan Brown
You can use any number of the XML libraries available on npm. Here's an example using the simply-named "xml" library:
您可以使用 npm 上可用的任意数量的 XML 库。这是使用简单命名的“ xml”库的示例:
var xml = require('xml');
response.set('Content-Type', 'text/xml');
response.send(xml(name_of_restaurants));
See the module's documentation for a description of how it converts JavaScript objects to XML. If you need things returned in a specific XML format, you'll have more work to do, of course.
有关如何将 JavaScript 对象转换为 XML 的说明,请参阅该模块的文档。如果您需要以特定 XML 格式返回的内容,当然还有更多工作要做。
回答by Christopher Dyke
As an update to this, it looks like res.type should be used instead as res.set does not give the same results.
作为对此的更新,看起来应该使用 res.type 代替,因为 res.set 不会给出相同的结果。
res.type('application/xml');
More information can be found in the API reference.
更多信息可以在 API 参考中找到。

