[英]How to insert npm uniqid modules in mysql database using nodejs. when i put on my code it display an error "TypeError: uniqid is not a function"
I am using nodejs with express and mysql.我正在将 nodejs 与 express 和 mysql 一起使用。 when i submit a form i found an error "uniqid is not a function".
当我提交表单时,我发现一个错误“uniqid 不是函数”。
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()
您正在使用
uniqid()
的值覆盖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"虽然它可能适用于第一次执行1 ,但后续调用将失败并显示错误“uniqid is not a function”
Change the name and use es6 let/const
instead of var
更改名称并使用 es6
let/const
而不是var
const uniqid = require('uniqid');
...
const newId = uniqid();
const insert_query = `INSERT INTO ... VALUES ("${newId}"...) `;
1 It doesn't, see Klaycon comment below 1不是,请参阅下面的 Klaycon 评论
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.当函数被执行时,它在设置任何值之前将
foo
声明为当前函数执行上下文的局部变量。
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
.然后引擎尝试用
foo()
设置它的值,但当时foo
是一个局部变量,而不是全局变量,它的值是undefined
。
And obviously, undefined
is not a function, hence the error, "foo is not a function".显然,
undefined
不是函数,因此会出现错误“foo 不是函数”。
tl;dr: be careful when naming your variables (and use let
/ const
). tl;dr:命名变量时要小心(并使用
let
/ const
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.