аналог document.getElementById в Node.JS
В html есть код <div id="content">Выделим этот элемент</div>, его мне нужно использовать в Node, а именно воткнуть содержимое в переменную. Код скрипта var elem = document.getElementById('content') работает только в ДжаваСкрипт. Подскажите, или ссылку на урок пришлите.
Для примера написал код создания папки по нажатию на кнопку, с именем которое должен ввести пользователь. server.js var express = require('express') var app = express() function reid() { var fs = require('fs') var newR = document.getElementById('peremennay').value fs.mkdirSync(newR) } app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html') }) app.get('/createDirectory', function (req, res) { try { reid() res.send(JSON.stringify({ created: 'success' })) } catch (erorr) { res.send(JSON.stringify({ created: 'failed' })) } }) app.listen(4000, function () { console.log('started at http://localhost:4000') }) index.html <html> <head> <script> document.addEventListener('DOMContentLoaded', function () { document.getElementById('createDirectory').addEventListener('click', function(e) { fetch('/createDirectory').then(r => r.json()).then(r => { alert(r.created) }) }) }) </script> </head> <body> <h1>Expressed</h1> <hr/> <div id="status"></div> <hr/> <textarea name="" id="peremennay" cols="30" rows="10">Введите название папки</textarea> <button id="createDirectory">Создать папку</button> </body> </html> Спасибо! |
оп оп, узнаю свои писули )...
server.js var express = require('express') var app = express() var fs = require('fs') var path = require('path') app.get('/', function (req, res) { res.sendFile(path.join(__dirname, '/index.html')) }) app.get('/createDirectory/:dirname', function (req, res) { try { fs.mkdirSync(path.join(__dirname, req.params.dirname)) res.send(JSON.stringify({ created: 'success' })) } catch (error) { res.send(JSON.stringify({ created: `failed ${error.message}` })) } }) app.listen(4000, function () { console.log('started at http://localhost:4000') }) index.html <html> <head> <script> document.addEventListener('DOMContentLoaded', function () { document.getElementById('createDirectory').addEventListener('click', function (e) { fetch(`/createDirectory/${document.getElementById('dirname').value}`).then(r => r.json()).then(r => { alert(r.created) }) }) }) </script> </head> <body> <h1>Expressed</h1> <hr /> <div id="status"></div> <hr /> <input id="dirname" placeholder="Введите название папки" type="text" /> <button id="createDirectory">Создать папку</button> </body> </html> чтобы POST засылать, надо в fetch указать method, и на стороне сервера нужен bodyparser... |
Спасибо! Работает!
|
Часовой пояс GMT +3, время: 04:40. |