简体   繁体   中英

Node JS: ReferenceError: require is not defined

I want to use MySQL database. I installed MySQL with command npm i mysql . In order to use it, I wrote:

var mysql = require('mysql');

But when I run the program, it shows ReferenceError: require is not defined error.

I wrote this line in home.ejs file within a script tag.

Home.ejs isn't the approriate file to write this line in. ejs files won't contains that much logic (except condition and loop over some element in your dom). Basically what you want to do is anodeJs script file which will connect to mysql, handle the request and serve your ejs files with your data.

Using express you'll have something like this in your node file :

app.get("/home",(req,res)=>{ res.render("home.ejs", {data : data}) (where data is what you get from your DB

By default require() is not a valid function in client side javascript. I recommend you look into require.js as this does extend the client side to provide you with that function.

you need to do your mysql processing before you get to the ejs template. Right now, you are trying to use require in a template, which is being rendered on the browser. You won't be able to do that without using a module loader like requirejs .

require() by default is a NodeJS function on the server side. You can use require.js like Abhilash said. It's bad practice to have mysql in the browser. Your username, password, and host will be exposed to the world.

The browser does not have an API that require modules. Also, this is something that you would do in a nodejs application (in the backend NOT the front end), typically in a .js file.

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