React js连接到数据库

时间:2019-02-22 02:42:53

标签: javascript mysql reactjs

如何将reactjs连接到mysql? 我已经安装了mysql,并且按照通用说明进行连接,但是它不起作用。出现错误“ TypeError:mysql.createConnection不是函数”。

下面是我的代码。

import React, { Component } from 'react';
import * as mysql from 'mysql';

class Users extends Component {


    constructor(props){


        const mysql = require('mysql');

        const connection = mysql.createConnection({
          host: 'localhost',
          user: 'root',
          password: '',
          database: 'react_prac'
        });
        connection.connect();
         console.log(connection);


        super(props);
    }

    render() { 
        return (  
            <div>
                DB
            </div>
        );
    }
}

export default Users;

我也想知道这是否正确。

谢谢。

1 个答案:

答案 0 :(得分:0)

将重要的MySQL移至import语句的顶部。可能需要对您不起作用

    import mysql from 'mysql';

还要确保始终将super用作构造函数的第一行

更新的代码:

   import React, { Component } from 'react';
   import mysql from 'mysql';
   class Users extends Component {
       constructor(props){
           super(props);
           const connection = mysql.createConnection({
           host: 'localhost',
           user: 'root',
           password: '',
           database: 'react_prac'
        });
       connection.connect();
       console.log(connection);
    }

render() { 
    return (  
        <div>
            DB
        </div>
    );
   }
 }

 export default Users;

更新:

  It seems DB connection is not possible from front end. It should be done in the backend, for better understanding check this answer

Error in MySQL library for Node.js