Expressjs响应为JSON和Xml
我正在做的:我正在尝试从数据库中为数据集生成json和xml输出 快速代码::我正在尝试JSON响应Expressjs响应为JSON和Xml,xml,json,node.js,express,node-mysql,Xml,Json,Node.js,Express,Node Mysql,我正在做的:我正在尝试从数据库中为数据集生成json和xml输出 快速代码::我正在尝试JSON响应 var express = require('express') , async = require('async') , http = require('http') , mysql = require('mysql'); var xml = require('xml'); var app = express(); var connection = mysql.creat
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var xml = require('xml');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'MyDatabase'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 3007);
app.use(express.static(__dirname + '/public/images'));
app.get('/Result/',function(request,response){
var name_of_restaurants;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM mas_buf_type', 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 });
//response.set('Content-Type', 'text/xml');
//response.send(xml(name_of_restaurants));
} );
} );
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
我的输出:
{
"restaurants": [
{
"Buf_Type_Id": 1,
"Buf_Type_Name": "Breakfast"
},
{
"Buf_Type_Id": 2,
"Buf_Type_Name": "Lunch"
},
{
"Buf_Type_Id": 3,
"Buf_Type_Name": "Dinner"
}
]
}
<Buf_Type_Id>1</Buf_Type_Id>
<Buf_Type_Id>2</Buf_Type_Id>
<Buf_Type_Id>3</Buf_Type_Id>
<restaurants>
<0>
<Buf_Type_Id>1</Buf_Type_Id>
<Buf_Type_Name>Breakfast</Buf_Type_Name>
</0>
</restaurants>
现在而不是
response.json({'restaurants' : name_of_restaurants });
我添加了这些行以获取XML
output
response.set('Content-Type', 'text/xml');
response.send(xml(name_of_restaurants));
输出:
{
"restaurants": [
{
"Buf_Type_Id": 1,
"Buf_Type_Name": "Breakfast"
},
{
"Buf_Type_Id": 2,
"Buf_Type_Name": "Lunch"
},
{
"Buf_Type_Id": 3,
"Buf_Type_Name": "Dinner"
}
]
}
<Buf_Type_Id>1</Buf_Type_Id>
<Buf_Type_Id>2</Buf_Type_Id>
<Buf_Type_Id>3</Buf_Type_Id>
<restaurants>
<0>
<Buf_Type_Id>1</Buf_Type_Id>
<Buf_Type_Name>Breakfast</Buf_Type_Name>
</0>
</restaurants>
输出:
{
"restaurants": [
{
"Buf_Type_Id": 1,
"Buf_Type_Name": "Breakfast"
},
{
"Buf_Type_Id": 2,
"Buf_Type_Name": "Lunch"
},
{
"Buf_Type_Id": 3,
"Buf_Type_Name": "Dinner"
}
]
}
<Buf_Type_Id>1</Buf_Type_Id>
<Buf_Type_Id>2</Buf_Type_Id>
<Buf_Type_Id>3</Buf_Type_Id>
<restaurants>
<0>
<Buf_Type_Id>1</Buf_Type_Id>
<Buf_Type_Name>Breakfast</Buf_Type_Name>
</0>
</restaurants>
1.
早餐
我们还可以清楚地看到,
正在生成。。。。这不是必需的…如何删除它?所以我四处寻找一个更好的对象到XML映射器。我尝试了三个,然后找到了一个我喜欢的(它易于使用,并且对您的应用程序很有意义)。丢弃旧的,改用:
这些标记之所以存在,是因为您正在将数组嵌入到“餐厅”中。相反,尝试将每个餐厅命名为对象数组:
…谢谢你的回复[+1]。。。。我会像你说的那样等待一个更好的答案……但我也尝试了你已经发布的答案。。。。请看编辑,你去吧!只是需要找到一个更好的对象到XML映射器。