【问题标题】:query the content from mysql in js在js中从mysql中查询内容
【发布时间】:2021-11-18 16:03:16
【问题描述】:

我想从 MySQL 检索内容到网页。我尝试使用 node.js,我在上面创建了一个服务器,但我找不到如何将它链接到网页。如何在节点中传递参数?

我需要根据链接中的参数从表中加载内容。 (标题、描述等) 例子: 本地主机:63342/MySite/project.html?projectname=mygame

网页参数提取代码:

<script>
            var params = window
                    .location
                    .search
                    .replace('?','')
                    .split('&')
                    .reduce(
                            function(p,e){
                                var a = e.split('=');
                                p[ decodeURIComponent(a[0])] = decodeURIComponent(a[1]);
                                return p;
                            },
                            {}
                    );
        </script>

Node.js 服务器代码:

const http = require("http");
http.createServer(function(request,response){

    response.end("Hello NodeJS!");

}).listen(3000, "127.0.0.1",function(){
    console.log("Сервер начал прослушивание запросов на порту 3000");
});

const mysql = require("mysql2");

const connection = mysql.createConnection({
    host: "localhost",
    user: "username",
    database: "databasename",
    password: "pass"
});

connection.connect(function(err){
    if (err) {
        return console.error("Ошибка: " + err.message);
    }
    else{
        console.log("Подключение к серверу MySQL успешно установлено");
    }
});

connection.query("SELECT * FROM ProjectsData",
    function(err, results, fields) {
        console.log(err);
        console.log(results); // собственно данные
        //console.log(fields); // мета-данные полей
    });

【问题讨论】:

  • 你正在寻找一个 ajax 实现,像 axios 这样的实现在这里会很好
  • 另外,在你的 node.js 服务器应用程序中,你需要定义一个实际的路由,可能是一个get 路由,它将提供这些数据

标签: javascript html jquery mysql node.js


【解决方案1】:

我将整个网站移到了 Node.js 主机上,使用 Handlebars 进行页面渲染,使用 express.router 进行参数管理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 2015-08-24
    • 2013-09-10
    • 1970-01-01
    相关资源
    最近更新 更多