简体   繁体   中英

How to connect to MySQL from JavaScript?

I know that for connecting to the database from JavaScript I need to mention the database credentials in plain JavaScript code. Therefore for a online application that would be a huge security risk. But in my case I want to write a small JavaScript application which is stored locally. So the credentials won't be shown to the world but just to the user I give the application, which is acceptable for me.

The motivation behind this is that I want to connect to an online database without a running PHP server, just from a JavaScript embedded in the local page. My goal is to provide an application that can be run by the user without the need for PHP and a server, except the database server. It's similar to a desktop application but running in the browser.

How can I connect from JavaScript to an online MySQL database? All other similar questions I found on Stack Overflow advices the thread starter against this usage for good reason but hadn't answered the question.

I heard that connecting to MySQL from JavaScript would be impossible. But how do, say, Windows 8 Metro Apps written in JavaScript handle that issue?

A backend repeater is always needed. For this issue you can set up a light-weight server that forwards your database accessing request to mysql server using, say node.js.

If you are focussing on a specific web browser, maybe you'll find a workaround. But if you're thinking on a local application independent from the user agent, you should follow the standards to reach a predictable behavior (or at least the best approach). In the W3C standards you have two options for storage:

Web Storage API : you're limited to key-value storage, but is very well supported .
Indexed Database API . I've no experience with it, but it's supported .

If you're not to limit the user context to a restricted machine and user agent, you can start with standard storage solutions as mentioned above and then enhance your app for more advanced browsers (perhaps even with MySQL!), as recommended in Progressive Enhancement

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