I created a simple node.js project using the command "express -e sample".
I have my javascript, css files under /public directory and ejs files under views and my server.js is in root directory.
I created a form page and when users submits it, i invoke a function in one of my js files which is under /public/javascripts.
Everything works perfectly. I now want to save the form input to my database(mysql) so i tried to get mysql but it failed. The alert statement said the object is undefined.
var database = require('mysql').Client;
However the same command works fine in server.js. It prints my database properties.
<input type="submit" onclick="processFormData();"/>
is the code that invokes processFormData();
function on the client-side (in the browser), once the user clicks the button.
Thus, var database = require('mysql').Client;
is also executed on the client.
Obviously, there is no require
in the browser; and even if there was require
and mysql
library in the browser - probably you would still want to make changes in DB from the server, not from the client (not sending to the client your DB credentials).
In order to do that, you should:
onclick
handler and let the user submit the form;Alternatively, if you want to use your current "write once, run anywhere" approach, you may be interested in alternative platforms such as Meteor and OPA language