Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 966
Jaowat Raihan Avatar asked Apr 21 '17 15:04

Jaowat Raihan


2 Answers

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

like image 190
mJehanno Avatar answered Sep 20 '22 02:09

mJehanno


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.

like image 21
Abhilash Avatar answered Sep 19 '22 02:09

Abhilash