最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node JS: ReferenceError: require is not defined - Stack Overflow

programmeradmin10浏览0评论

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 badges
Add a comment  | 

5 Answers 5

Reset to default 5

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.

发布评论

评论列表(0)

  1. 暂无评论