简体   繁体   中英

Node.js / Express - how to think about client-side database work? (e.g. can't use require())

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM