Spaces:
Sleeping
Sleeping
File size: 1,732 Bytes
abed4cc 550ce38 40f1235 abed4cc 5d38af1 550ce38 2bdd039 550ce38 6c4d40b 550ce38 0cb0cc3 550ce38 c26c406 d2516ec c26c406 550ce38 d2516ec 550ce38 2bdd039 550ce38 2bdd039 abed4cc 0cb0cc3 abed4cc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
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}`);
}); |