Node JS: ReferenceError: require is not defined

I want to use a MySQL database. I installed MySQL with the command npm i mysql

. To use it, I wrote:

var mysql = require('mysql');

      

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

I wrote this line in my home.ejs file in the script tag.

+3


source to share


5 answers


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

Using Express, your node file will have something like this:



app.get("/home",(req,res)=>{ res.render("home.ejs", {data : data})

(where data is what you get from your DB

+4


source


By default, require () is not a valid JavaScript javascript side function. I recommend that you look into require.js as it extends the client side to provide this functionality for you.



+3


source


you need to do your mysql processing before going to the ejs template. Right now you are trying to use require

in a template that is rendered in a browser. You cannot do this without using a module loader like requirejs .

+2


source


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

+2


source


There is no API in the browser, which is require

modules. Also, this is what you would do in a nodejs app (in the backend NOT front end), usually in a .js file.

+1


source







All Articles