S
S
squadbrodyaga2020-10-20 19:43:50
Node.js
squadbrodyaga, 2020-10-20 19:43:50

Can you help me deal with POST requests in Node JS?

Hello, I'm taking a Node JS course and I'm going crazy.

In general, I want to learn how to send data from the registration form, but I have some kind of jamb, after entering the data and clicking on the button, I get a page with the inscription: Cannot POST /routes/register.js

If anything, my structure looks something like this:
____________________________________
HTML (folder)
- register.html
- index.html

routes (folder)
- register.js

index.js (here I have all sorts of crap, connecting modules, routes and starting the server)
____________________________________

Here are the contents of these files:

CODE In register.html

spoiler

<form action="../routes/register.js" method="POST">
 <input type="text">
 <input type="email">
 <input type="password">
 <button>Регистрация</button>
</form>



CODE IN register.js
spoiler

const express = require('express')
const path = require('path')
const router = express.Router()

router.get('/register', async (req, res) => {
    res.sendFile(path.join(__dirname, '../HTML', 'register.html'))
})

router.post('/register', async (req, res) => {
    req.session.isAuth = true    // не понимаю, что это за строчка и для чего она нужна
    res.redirect('/index')
})

module.exports = router



Bottom line: Cannot POST /routes/register.js
P.S: Is it normal for me to accept both POST and GET requests in the same route? It's just that in some video the guy created a separate folder and file for POST requests.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
d-sem, 2020-10-20
@squadbrodyaga

req.session.isAuth = true // I don't understand what this line is and what it is for

Writes a value to the session. https://xsltdev.ru/nodejs/tutorial/sessions/
Cannot POST /routes/register.js

Because action is not a path to a file. and the path to the route.
Therefore, you need to either remove the action (because the uri does not change, but the route changes).
or write action="/register"

The error occurs because the POST /routes/register.js route does not exist, because it does:
GET /register
POST /register
As reported.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question