Search code examples
mysqlnode.jsexpressknex.js

Why is Knex not able to insert into mysql?


I am trying to insert a row of values into MySQL database using Knex but I am getting a weird error. The table and database exist and the fetch API works perfectly but I am not able to insert values using sifnUp route.

const db= knex ({
  client: 'mysql2',
  connection: {
    host: '127.0.0.1',
    port: 3306,
    user: 'root',
    password: '',
    database: 'transaction_app'
  }
});

app.get('/', (req, res) => {
  res.send('App is running')
});

app.post('/signUp', (req, res,db) => {
  const {name, email, mobile, password}=req.body;
  const hash=bcrypt.hashSync(password, 10);

  db('users')
  .insert({
    name: name,
    email: email,
    mobile: mobile,
    password: hash
  })
  .then(data=>{
    res.send(data);
  })
  .catch(err=>{
    res.send(err);
  })
});

app.get('/fetch',(req,res)=>{
  db.select('*').from('users')
  .then(data=>{
    res.send(data);
  })
  .catch(err=>{
    res.send(err);
  })
})

app.listen(3000, () =>{
  console.log('Server started on port 3000');
});

The error that is consoled is this

Server started on port 3000
users
TypeError: Cannot read properties of undefined (reading 'insert')
    at D:\Documents\Atoa Assignment\server.js:35:3
    at Layer.handle [as handle_request] (D:\Documents\Atoa Assignment\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\Documents\Atoa Assignment\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (D:\Documents\Atoa Assignment\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (D:\Documents\Atoa Assignment\node_modules\express\lib\router\layer.js:95:5)
    at D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:346:12)
    at next (D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:280:10)
    at cors (D:\Documents\Atoa Assignment\node_modules\cors\lib\index.js:188:7)    at D:\Documents\Atoa Assignment\node_modules\cors\lib\index.js:224:17

This is the Postman Screenshot. enter image description here


Solution

  • Your error:

    app.post('/signUp', (req, res,db) => {
      const {name, email, mobile, password}
    

    The third parameter is the express next, not db.

    Inside the route you assign next() to db. (req,res,"db") Must be (req,res, next).

    When you call db.insert it is not referring of the top of your code

    const db= knex ({
    

    So you dont db.insert but next.insert (which obviously does not exist).

    As you are not using the next handler of express, simply delete db in (req,res,db) and it should work.

    Remember the scopes of variables in Javascript. An Example