gpt4 book ai didi

node.js - 如何使用 ExpressJS 在 XML 中响应?

转载 作者:IT老高 更新时间:2023-10-28 22:04:14 26 4
gpt4 key购买 nike

我有一个简单的代码,它为特定路由提供 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 响应?

最佳答案

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

var xml = require('xml');

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

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

关于node.js - 如何使用 ExpressJS 在 XML 中响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21398279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com