【问题标题】:How can I respond in XML using ExpressJS?如何使用 ExpressJS 在 XML 中响应?
【发布时间】:2014-02-19 07:40:31
【问题描述】:

我有一个简单的代码,它为特定路由提供 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'));
});

我怎样才能做出与上面的 JSON 等效的 XML 响应?

【问题讨论】:

    标签: node.js express node-mysql


    【解决方案1】:

    您可以使用 npm 上提供的任意数量的 XML 库。下面是一个使用简单命名的“xml”库的示例:

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

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

    【讨论】:

    • 感谢我从您的回答中得到了 xml 响应 .... 但请查看此链接 stackoverflow.com/q/21399572/1083093 .... 而不是两个只有一列正在生成
    • response.set('Content-Type', 'application/xml') - 我读过这个更正确,只是把它扔在那里
    • 如果你使用 'application/xml' 你需要在某处指定字符集
    • TypeError: res.set 不是函数
    • 如果我能喜欢这个一百次,我会的。花了 3 多个小时后,您的答案是我发现的第一个真正有效的答案。
    【解决方案2】:

    作为对此的更新,看起来应该使用 res.type 来代替,因为 res.set 不会给出相同的结果。

    res.type('application/xml');
    

    更多信息可以在in the API reference找到。

    【讨论】:

    • 这个答案有帮助,但是res.header('Content-Type', 'text/xml'); 对我来说更有意义,特别是当你有很多其他标题时
    猜你喜欢
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 2012-12-16
    相关资源
    最近更新 更多