I am using nodejs with express and mysql. when i submit a form i found an error "uniqid is not a function".
var express = require('express');
var router = express.Router();
var uniqid = require('uniqid');
var db = require('../db');
router.post('/create',function(req,res,next){
var full_name = req.body.fullname;
var email = req.body.email;
var password= req.body.password;
var mobile_no = req.body.mobile_no;
var uniqid = uniqid();
var insert_query = `INSERT INTO users (user_uid,full_name,email,mobile_no,password) VALUES ("${uniqid}","${full_name}","${email}","${mobile_no}","${password}") `;
db.query(insert_query,function(err,result){
if(err) throw err;
res.redirect('/signup');
});
});
module.exports = router;
You're overriding the uniqid
module with the value from uniqid()
var uniqid = require('uniqid');
...
var uniqid = uniqid();
While it might work on the first execution 1 , subsequent calls will fail with that error "uniqid is not a function"
Change the name and use es6 let/const
instead of var
const uniqid = require('uniqid');
...
const newId = uniqid();
const insert_query = `INSERT INTO ... VALUES ("${newId}"...) `;
1 It doesn't, see Klaycon comment below
Let's take this code for example :
var foo = () => "test" function test() { var foo = foo() } test()
As you can see, it has the same error you have. This is because you are naming your local variable like your global variable.
What happens is what is called Hoisting . When the function gets executed, it declares foo
as a variable local to the current function execution context before setting it any value.
Then the engine tries to set its value with foo()
, but at that time foo
is a local variable, not the global one, and its value is undefined
.
And obviously, undefined
is not a function, hence the error, "foo is not a function".
tl;dr: be careful when naming your variables (and use let
/ const
).
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.