Как реализовать маршрутизацию на чистом node js (без express)?
Как реализовать нормально маршрутизацию на чистом node js (без express)? Код, который я привожу ниже, устраивал меня до тех пор, пока я не столкнулся с get-запросами с параметрами. Тогда я понял, что его надо переписывать, но не могу найти примеров. Может есть у кого примеры маршрутизации на чистой ноде или идеи как сделать?
const server = http.createServer((req, res) => {
let filePath = path.join(__dirname, 'public', req.url === '/' ? 'login.html' : req.url)
const ext = path.extname(filePath)
let contentType = 'text/html'
switch (ext) {
case '.css':
contentType = 'text/css'
break
case '.js':
contentType = 'text/javascript'
break
default:
contentType = 'text/html'
}
if (!ext) {
filePath += '.html'
}
fs.readFile(filePath, (err, content) => {
if (err) {
fs.readFile(path.join(__dirname, 'public', 'error.html'), (err, data) => {
if (err) {
res.writeHead(500)
res.end('Error')
} else {
res.writeHead(200, {
'Content-Type': 'text.html'
})
res.end(data)
}
})
} else {
res.writeHead(200, {
'Content-Type': contentType
})
dbConnect()
if (req.url === '/login' && req.method === 'POST') {
loginApp(req, res)
} else if (req.url === '/registration' && req.method === 'POST') {
regApp(req, res)
} else if (req.url === '/new_post' && req.method === 'POST') {
createNewPost(req, res)
} else if (req.url === '/main' && req.method === 'POST') {
deletePost(req, res)
} else if (req.url === '/main') {
renderPosts(res)
} else {
res.end(content)
}
}
})
})
const PORT = process.env.PORT || 5000
server.listen(PORT, () => {
console.log(`Server has been started on ${PORT}...`)
})
Даже, например, на адрес /main не могу обработать get-запрос с параметрами.
Ответы (1 шт):
Автор решения: Данила
→ Ссылка
- Отправляйте с фронта POST-запрос, в body положите некий ключ.
- На сервере принимаете POST-запрос, проверяете на предмет данного ключа, выполняете необходимые операции, и отправляете ответ на фронт.
- На фронте получаете данные.
- вот вам и "GET"-запрос.