Spaces:
Sleeping
Sleeping
const express = require('express'); | |
const xml2js = require('xml2js'); | |
const js2xmlparser = require('js2xmlparser'); | |
const app = express(); | |
app.use(express.json()); | |
// Функция преобразования JSON в XML | |
app.post('/to_xml', (req, res) => { | |
try { | |
const jsonInput = req.body.input; | |
if (!jsonInput) { | |
return res.status(400).json({ error: 'Отсутствует параметр input в теле запроса.' }); | |
} | |
const xmlOutput = js2xmlparser.parse("root", jsonInput); | |
res.type('application/xml'); | |
res.send(xmlOutput); | |
} catch (error) { | |
console.error(error); | |
res.status(500).json({ error: 'Произошла ошибка сервера при преобразовании JSON в XML.' }); | |
} | |
}); | |
// Функция преобразования XML в JSON | |
app.post('/to_json', (req, res) => { | |
try { | |
const xmlInput = req.body.input; | |
if (!xmlInput) { | |
return res.status(400).json({ error: 'Отсутствует параметр input в теле запроса.' }); | |
} | |
const parser = new xml2js.Parser({ | |
explicitArray: false, | |
charkey: 'value', | |
attrkey: 'attributes', | |
trim: true, | |
}); | |
parser.parseString(xmlInput, (err, result) => { | |
if (err) { | |
return res.status(500).json({ error: 'Произошла ошибка при разборе XML.' }); | |
} | |
res.json(result); | |
}); | |
} catch (error) { | |
console.error(error); | |
res.status(500).json({ error: 'Произошла ошибка сервера при преобразовании XML в JSON.' }); | |
} | |
}); | |
const port = 7860; | |
app.listen(port, () => { | |
console.log(`Сервер запущен на порту ${port}`); | |
}); |