【问题标题】:React js connect to database反应js连接到数据库
【发布时间】:2019-07-16 02:08:14
【问题描述】:

如何将我的 reactjs 连接到 mysql? 我已经安装了 mysql 并按照通用说明进行连接,但它不起作用。它得到一个错误“TypeError: mysql.createConnection is not a function”。

下面是我的代码。

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;

我也想知道这是否正确。

谢谢。

【问题讨论】:

    标签: javascript mysql reactjs


    【解决方案1】:

    将重要的 MySQL 移到导入语句的顶部。可能 require 不适合你

        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

    【讨论】:

    • 错误提示“TypeError: Net.createConnection is not a function”。
    • this._socket = this.config.socketPath ? Net.createConnection(this.config.socketPath) : Net.createConnection(this.config.port, this.config.host); // 将套接字连接到连接域
    • @vinceunggoy。最新的错误与 mysql create connection 无关。看起来您原来的问题现在已经解决了
    • 是的,但它得到一个新的错误。 TypeError: Net.createConnection 不是函数
    • @vinceunggoy 你不能在网络浏览器中创建 MySQL 连接我的意思是反应。它应该只在 Node 后端模块中完成。检查此以更好地理解stackoverflow.com/questions/38005968/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2015-11-14
    • 2018-10-03
    • 2011-12-04
    • 1970-01-01
    相关资源
    最近更新 更多