如何使用ExpressJS在XML中进行回应? [英] How can I respond in XML using ExpressJS?

查看:171
本文介绍了如何使用ExpressJS在XML中进行回应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple code that gives a JSON response for a specific route. Here's my current code:

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?

How can I make an XML response equivalent to the JSON above?

推荐答案

您可以使用npm上可用的任意数量的XML库。以下是使用简单命名的 xml 库的示例:

You can use any number of the XML libraries available on npm. Here's an example using the simply-named "xml" library:

var xml = require('xml');

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

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

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.

这篇关于如何使用ExpressJS在XML中进行回应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆