【问题标题】:why .Net.createConnection doesn't work on a browser and how to solve this?为什么 .Net.createConnection 在浏览器上不起作用以及如何解决这个问题?
【发布时间】:2020-10-03 13:12:02
【问题描述】:

我正在尝试与我的 Web 应用程序建立数据库连接(我正在使用 XAMPP - phpmyadmin)。

在这个里程碑中,我第一次遇到了 Node.js,并设法通过使用 browserify 使 require() 函数工作。这是我在register.php 上单击“注册”按钮时执行的 javascript 文件。

var mysql = require('mysql');

var thisUser = mysql.createConnection({
    host: "localhost",
    user: "admin1",
    password: "password",
    database: "db_mymindmapper"
});


------------- WORKS UNTIL HERE -------------

thisUser.connect(function(error){
    if(!error) {

        alert("NODE CONNECTED TO MYSQL SERVER");
        var sql = "INSERT INTO student_demographics (first_name) VALUES ('YOU DID IT MF')";

        thisUser.query(sql, function(err, result) {
            if(!err){
                alert("result = " + result);

            }else{
                throw err;
            }
        });

    }else{
        throw error;
    }
});

当我使用我的 register.php 文件在浏览器上运行它时,它会在控制台上显示以下错误:

Uncaught TypeError: Net.createConnection is not a function
    at Connection.connect (bundle.js:34538)
    at HTMLInputElement.check_Register (bundle.js:43660)
connect @ bundle.js:34538
check_Register @ bundle.js:43660

但是,当我在 CMD 中使用 node signUp.js 运行它时,它可以完美运行,并且数据会转到 phpmyadmin 上的表中。

我知道这是由提供的question 中的这个原因引起的:“您必须仅在 Node.js 上运行此特定模块,不能在 Web 浏览器中运行它。”

我的问题:

是否有任何可能的方式在浏览器上运行,以便用户在访问register.php 站点时可以注册?我需要更改代码的整个结构吗?我需要require('http') 来设置 Node.js 服务器吗?

【问题讨论】:

    标签: javascript mysql node.js connect


    【解决方案1】:

    所以为了回答我自己的问题,我确实通过创建一个 node.js 服务器来解决这个问题。为此,我使用了 Visual Studio Code 中的终端(CMD 也可以使用)。

    cd directoryOfTheApplication //(change the directory of the terminal)
    npm init   //(creates a package.json file within directory of the application)
    npm install express //(modifies the package.json and add modules within node-modules folder)
    

    在目录中创建一个新的 .js 文件(我叫我的server.js)。

    //USE `nodemon scripts/server.js` on Terminal to autosave the server files.
    
    //My modules
    const express = require("express");
    const morgan = require("morgan"); //GET INFORMATION ABOUT THE SERVER REQUESTS (OS, Browser,time, ...)
    const mysql = require("mysql");
    
    const app = express();
    
    app.use(morgan('combined')); //'short', 'combined'
    
    app.get("/users/:id", (req, res) => {
    
        const userID = req.params.id;
        console.log("Fetching user with id : " + userID); 
    
        //get data from DB
        const connection = mysql.createConnection({
            host: "localhost",
            user: "admin1",
            password: "secret",
            database: "myDB"
        });
        let sql = "SELECT * FROM student_demographics WHERE id =?";
        connection.query(sql, [userID], (err, rows, fields) => {
            console.log("Fetching users was successful");
            res.json(rows);
        });
    
        //res.end();
    });
    
    app.get("/", (req, res)=>{
        console.log("responding to root route");
        res.send("hello world from root");
    });
    
    app.get("/users", (req, res)=>{
        const user1 = {
            firstName: "name1",
            lastName: "name2"
        };
        const user2 = {
            firstName: "name3",
            lastName: "name4"
        };
        res.json([user1, user2]);
    });
    
    app.listen(81, ()=>{
        console.log("Server running on port 81");
    });
    

    再次在终端中,您可能希望安装nodemon,这样您就不必手动启动服务器。这将在保存文件时刷新和更新服务器(在本例中为 server.js)。此外morgan 基本上会收集有关用户请求的信息。在终端中它看起来像这样:

    PS C:\inetpub\wwwroot\mymindmapper> nodemon scripts/server.js
    [nodemon] 2.0.4
    [nodemon] to restart at any time, enter `rs`
    [nodemon] watching path(s): *.*
    [nodemon] watching extensions: js,mjs,json
    [nodemon] starting `node scripts/server.js`
    Server running on port 81
    Fetching user with id : 1
    Fetching users was successful
    ::1 - - [14/Jun/2020:11:15:20 +0000] "GET /users/1 HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 
    Safari/537.36"
    

    另一个模块mysql 是为了这个例子,但我想它可以与任何模块一起使用。我在YT上基本上是按照这个聪明人的教程来的。

    设置快递:NodeJS REST API: Super Simple Setup - Express & NPM (Ep1)

    设置数据库:NodeJS REST API: Connecting to MySQL (Ep 2)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 2021-10-24
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      相关资源
      最近更新 更多