Source:  Twitter logo

How can I connect MySQL to ReactJS? Are there any examples or tutorials which explain this that I can follow?

I wrote the following code, but get errors:

var React = require('react');
var ReactDOM = require('react-dom');

var mysql = require('mysql');
var express = require('express');
var app = express();

var fs = require('fs');

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : ' ',
    database : 'node'
});

connection.connect();

app.post('/users', function(req, res) {

    var user = req.body;

    var query = connection.query('INSERT INTO signup SET ?', user,  function(err, result) {

    });
    res.end('Success');
});

What is wrong with this code?

The error you mentioned in the comments, it's because you are trying to require fs module, however in doesn't exist in the front-end with webpack by default. Of course you could provide a polyfill but that's not what's being asked here.

So let's take a step back. How can one connect to MySQL?

The usual method to connect to MySQL is making a TCP connection, well normally MySQL driver does this for you so you don't need to know exactly how, but this means you can't really connect from Javascript on browser.

However you can do this in the backend/server-side with node.js or any other server-side language. The way normally this is done is that, the backend exposes an HTTP(s) API that can be accessed by the front-end. This could be a REST API, GraphQL, or even something as complex as SOAP(which I don't suggest) and through this API, the database is exposed. This is a common design in the usual web applications and tiered architectures.

Meanwhile, you can with Mysql Labs HTTP plugin, you can expose your database to the browser without writing any API of your own, but of course if you go that path, you gotta know what your doing and have top security standards.

0 users liked answer #0dislike answer #00
Farid Nouri Neshat profile pic
Farid Nouri Neshat

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).