How to have the server read query strings then send that page a confirmation

the handler is a JavaScript function, the function (request, response) { ... }. put the code between the { and }.

1 Like

I just moved the handler to the top of my code but I dont see it working

app.get("/register", function (request, response) {
  response.sendFile(__dirname + "/public/trolled/register/register.html");
app.route("/register")
  .post(async (req, res) => {

  // handle POST request to the registration page
  // extract the user's information from the form
  const { username, email, password } = req.body;
  // validate form inputs
  if (!username || !email || !password) {
    return res.status(400).send("Please fill out all fields");
  }

  // see if the email already exists in the database
  const emailExists = await new Promise((resolve, reject) => {
    db.get(
      SELECT * FROM registrations WHERE email = ?`,
      [email],
      (err, row) => {
        if (err) reject(err);
        resolve(row !== undefined);
      }
    );
  });

  if (emailExists) {
    return res.status(400).send("Email already exists");
  }

  // give user an ID
  var userID = base64.encode(email);

  // hash password
  const saltRounds = 10;
  const hashedPassword = await bcrypt.hash(password, saltRounds);

  console.log([username, email, hashedPassword, userID]);

  db.run(
    INSERT INTO registrations (username, email, password, userID) VALUES (?, ?, ?, ?),
    [username, email, hashedPassword, userID],
    function (err) {
      if (err) {
        return console.error(err.message);
      }
      console.log("A row has been inserted with rowid ${this.lastID}");
    }
   )
 });
});```

two problems: (i) your handlers got nested up again; and (ii) that logic for handling the submitted credentials is still registered on the /register route, you haven’t successfully moved it to /redirect.

be careful with these details!

1 Like

So change form action in /register to be /register instead of /redirect?

yeah, that would work too.

Alright it works
image
But I want it to redirect to /login when completed which leads to the question of how would I have /redirect know where you came from. i.e. /register or /login to then redirect the user to /login if they came from /register or /home if they came from /login.

ooh way to go!

let’s go over the proposed design:

  1. user goes opens /register in their browser, which makes a GET request /register.
  2. server receives GET request to /register, sends HTML page with a form
  3. user submits form, which makes POST request to /register
  4. server receives POST request to /register, adds user to database, sends redirect to /login
  5. browser receives redirect to /login, makes GET request to /login
  6. server receives GET request to /login, sends HTML page with a form

but in this whole picture, there is no /redirect route used. to clarify, redirection is a kind of HTTP response that one of your route handlers can send to the browser. if you actually want a /redirect route that does something, then describe what it does and how it fits in.

or if you’re in agreement with the sketch above, you can do the redirect in step 4 within the same handler where you’ve added the user to the database. see the express API reference for how to send a redirect as the response to that POST. someone else using your account was asking about redirects in express too: Express won't get a subdomain file - #9 by wh0 maybe see if there’s anything helpful in that thread

1 Like

Yeah that was me making that post, In this post I just tried a different approach.

I have a quick question, how would I have a variable in server.js be able to interact with other js files which is what I’m trying to do below

     app.get("/", function (request, response) {
    response.sendFile(__dirname + "/trolled");
      res.db.get(`CREATE VIEW [UserList] AS SELECT * FROM registrations`);
    var UserListhtml = db.get(`SELECT * FROM [UserList]`);
  });

I’m trying to make a database show in /trolled (temporarily) but I don’t think the varible UserListhtml is going through to /trolled.

right, it would stay on the server side as it is. this gets into how to send dynamic data as part of a response.

see this guide on how to have the server combine javascript values with a “template” to send back to the browser.

1 Like

Whenever I try to implement the template I get:
Error: Failed to lookup view "sqltest" in views directory "/app/views"
When I have a html file I you would usually put

app.get("/", function (request, response) {
  response.sendFile(__dirname + "/index.html");
});

But because the pug templates use

app.get('/', (req, res) => {
  res.render('index', { title: 'Hey', message: 'Hello there!' })
})

It doesn’t seem to load.

is that file in that views directory?

I don’t have a views file, It’s just in public/trolled/sqltest/sqltest.pug.

move that to views/sqltest.pug

Should the views folder be the first folder

the templates should be in the folder called “views” according to that error message

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.