Dev*_*ath 25 node.js express node-mysql
我有一个简单的代码,为特定路由提供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'));
});
Run Code Online (Sandbox Code Playgroud)
如何使XML响应等效于上面的JSON?
Eth*_*own 39
您可以使用npm上可用的任意数量的XML库.以下是使用简单命名的" xml "库的示例:
var xml = require('xml');
response.set('Content-Type', 'text/xml');
response.send(xml(name_of_restaurants));
Run Code Online (Sandbox Code Playgroud)
有关如何将JavaScript对象转换为XML的说明,请参阅该模块的文档.如果您需要以特定XML格式返回的内容,当然还有更多工作要做.
小智 12
作为对此的更新,看起来应该使用res.type,因为res.set不会给出相同的结果.
res.type('application/xml');
Run Code Online (Sandbox Code Playgroud)
可以在API参考中找到更多信息.
| 归档时间: |
|
| 查看次数: |
46336 次 |
| 最近记录: |