0

I've been through a number of Node.js, Express, and other tutorials/posts, and I'm struggling with how to think about connecting to a database on various pages throughout a webapp.

I would like to run a Node.js app (with a server.js file that connects to a database) and then query that database as needed on every page throughout the app.

So if I have an inventory.html page I should be able to have javascript that queries the inventory table and displays various inventory items throughout that html page.

Problem #1. I can't find a way to use mysql on any client-side pages, since javascript can't use node's require() function client-side. As detailed in this StackOverflow post ("require is not defined").

Problem #2. I can't figure out an elegant way to pass a database connection to other pages in my app. A page can send a POST request back to the server.js file, but this really isn't as flexible as I want.

I'm really looking for the modern, preferred way to do a bunch of PHP scripting in my Node app. Can anyone guide me to the right way to do this? Thank you!

  • 1
    You're thinking about this all wrong IMO. It seems that you are confusing client side with server side **because** they both happen to be javascript. Think of your node app as a php app and then ask yourself about your **Problem #1** again. It should then become obvious that you can't use a mysql server side connection on the client side no matter what the server is written it. Just because the server is javascript does not change the fundamentals of the communication and limitations of the basic web stack client/server. – gforce301 Apr 11 '18 at 18:10
  • _this really isn't as flexible as I want_ What do you mean ? It seems that Ajax is relatively flexible to handle this kind of situation. And why do you use PHP in parallel ? – TGrif Apr 11 '18 at 18:11
  • Right thank you, but really my question is - how can I best query a sql database, to display data on the client-side? –  Apr 11 '18 at 18:46

1 Answers1

1

You just can't directly call mysql from the client. Even if it worked imagine that anybody could modify the SQL queries and access all your data.

The only way how to do it is this:

js client app ------> js server app -------> mysql

You just must have 2 apps: one running in the user's browser sending requests to the server and the other running on the server answering the requests.

Jan Steuer
  • 141
  • 4