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.
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.
Share Improve this question edited Apr 21, 2017 at 17:34 Utkarsh Dubey 77612 silver badges33 bronze badges asked Apr 21, 2017 at 15:33 Jaowat RaihanJaowat Raihan 2812 gold badges3 silver badges14 bronze badges5 Answers
Reset to default 5Home.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.