Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Net.createConnection is not a function(…)

Tags:

mysql

reactjs

Using mysqljs, I want to query some data from my local db and render them with react. This is what I did so far:

import React from 'react';
var mysql      = require('mysql');
var connection = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password: '',
    database: 'pep'
});

connection.connect();
var Menu=React.createClass({
    data : function (){
        connection.query('Select * from '+this.props.table, function(err, rows, fields){
            if(err) throw err;
            console.log(rows);
        })
    },
    render : function () {
        return (
            <div>
                <button onClick={this.data}>click</button>
            </div>
        );
    }
});
export default Menu;

(Another file is using the Menu component and passing the props to Menu)

Nothing is displayed and it came with this error in the bowser's console:

Connection.js:91 Uncaught TypeError: Net.createConnection is not a function
    at Connection.connect (webpack:///./~/mysql/lib/Connection.js?:91:13)
    at eval (webpack:///./src/Menu.js?:24:12)
    at Object.<anonymous> (http://localhost:3000/static/js/bundle.js:2983:2)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:556:30)
    at fn (http://localhost:3000/static/js/bundle.js:87:20)
    at eval (webpack:///./src/Combobox.js?:18:13)
    at Object.<anonymous> (http://localhost:3000/static/js/bundle.js:3121:2)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:556:30)
    at fn (http://localhost:3000/static/js/bundle.js:87:20)
    at eval (webpack:///./src/App.js?:18:17)

Why is that? How can I fix this or what should I do in order to get my data from the db using react?

like image 298
hhelbawi Avatar asked Mar 05 '26 11:03

hhelbawi


1 Answers

mysqljs relies on Node's net library. You don't have this API in your browser, so you won't be able to use the library this way without major changes.

You shouldn't establish a direct connection from the client's browser to your backing database anyway, as your mysql database server is not necessarily built for this use case. Instead, publish your data via a dedicated web server as RESTful web services. You could for example use Node.js and the restify framework for that purpose.

like image 72
TimoStaudinger Avatar answered Mar 07 '26 23:03

TimoStaudinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!