简体   繁体   中英

I am trying to connect to postgres database from Node JS/Express. No response in Postman

At one point, the port was active and working, but no response in Postman.

And now it doesn't even recognize express even though it is included. Can someone please give me a hand, I have been trying to solve this for days now...

I tried to change to connect to a postgres database using knex, created the database in Pg admin, but it doesn't work. I wanted to have several routes to login, register and delete user profile, but it seems like Express is not working for some reason. I tried to change .catch in app.post(register) into .catch (err => res.json(err)), also I installed corse extension for Chrome but it didn't work either. I modified some words from the code (from my mother tongue so it is easier to review, I apologize if there is a place I missed... I had to paste the entire code because the mistake could be in the part I omit so.. At this point, in the output, Express is not recognized as installed.

const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');


const app = express();
app.use(bodyParser.json());
app.use(cors());

let db = knex({
    client: 'pg',
    connection: {
      host : '127.0.0.1',
      user : 'postgres',
      password : '12345',
      database : 'users'
    }
  });
/*app.get('/', (req, res) => {
  db.select('*').from('users').then(data => {res.json(data)});
})*/
//USER LOGIN
  app.post('/signin', (req, res) => {
    db.select('email', 'hash').from('login')
      .where('email', '=', req.body.email)
      .then(data => {
        const isValid = bcrypt.compareSync(req.body.password, data[0].hash);    
        if (isValid) {
        return db.select('*').from('login')
        .where('email', '=', req.body.email)
        .then(user => {
          res.json(user[0])
        })
        .catch(err => res.status(400).json('Cannot find user'))
        } else {
          res.status(400).json('Incorrect log in data')
        }
       })
       .catch(err => res.status(400).json('Incorrect data'))
    });
// REGISTER USER
    app.post('/register', (req, res) => {
      const {email, name, password} = req.body;
      const hash = bcrypt.hashSync(password);
          db.transaction(trx => {
            trx.insert({
              hash: hash,
              email: email
            })
            .into('login')
            .returning('email')
            .then(loginEmail => {
                return trx('users')
                  .returning('*')
                  .insert({
                    email: loginEmail[0],
                    name: name,
                    resgistered: new Date()
                  })
                .then(user => {
                  res.json(user[0]);
                })
            })
            .then(trx.commit)
            .catch(trx.rollback)
          })
          .catch(err =>res.json(err))
    });
// user profile
    app.get('/profile/:id', (req, res) => {
        const {id} = req.params;
        db.select('*').from('users').where( {id: id})
        .then(user => {
        if (user.length) {
        res.json(user[0])
        } else {
        res.status(400).json('User not found')
        }
        });
    });

    app.get('/allusers', (req, res) => {
      //const {id} = req.params;
      //db.select('*').from('korisnici').then(data => {console.log(data)});
      db.select('*').from('users').then(data => {res.json(data)});
    });
//delete user
app.delete('/users/:name', (req, res) =>{
  const email = req.params.email;
  db.select()
    .from('users').where({email: email}).del()
    .then((users) =>{
        db.select()
        .from('login').where({email: email}).del()
        .then(() => {
            res.json(`user ${email} deleted`);
        });
    }).catch((error) => {
        console.log(error);
    });
});
//APPLICATION PORT
app.listen(3000, () =>{
    console.log(('Port 3000 active'));
    //res.send('Database active at port 3000')
});

Make sure you installed pg module:

 npm install pg --save

Are you sure your db is called users ? If so then in you case you need a login table in users db. Then also insert some data from pg admin to your users.login .

You may also try to query your data directly from pg admin using SQL query to make sure that data is actually there:

SELECT * FROM users.login;

Then create the following route:

app.get('/', (req, res) => {
  db.select('*').from('login').then(data => {
    console.log(data);
    res.json(data);
  });
});

Then try sending request from Postman GET http://localhost:3000 .

Note: I would suggest you to use the correct naming of tables in db, not sure you wanted to call a table login . And try using async\\await instead of nesting with .then

Another solution would be to create a project from scratch following this simple tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM