我是node的新手.js和mySQL


var app=express();


app.listen(9999,function(){ //I'm using 9999 port and I use Localhost
    console.log('Server is running');
})

//connect mySQL
var client=mysql.createConnection({
    user:'root',
    password:'pswd' //for Question
});

我使用9999端口并在localhost上打开服务器.

我有html.这只是测试html文件(minuk\u test.html)

--主要.js公司--

app.get('/store/restaurant_info',function(request,response){
    client.query('SELECT * FROM RESTAURANT_INFO',function(error,result,fields){
        if(error){
            console.log('Query syntax error');
        }else{
            response.json(result);
            console.dir(result[0].name);
            console.log('check sending data');
        }
    });
});

app.get('/Project/html/minuk_test.html',function(request,response){
    fs.readFile('../html/minuk_test.html','utf-8',function(error,data){
        if(error){
            console.log('Loading minuk_test.html is failed');
        }
        response.send(data);
    })
})

这是我的html代码.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API TEST</title>
    <link rel="stylesheet" href="/minuks_test.js">
</head>
<body>
    <h1>Test</h1>
    <div id="restaurant">
        <span></span>
        <span></span>
    </div>
</body>
</html>

这是我的javascript

--javscript文件--

import fetch from "node-fetch";

function getAPI(){
    const url=`http://127.0.0.1:9999/store/restaurant_info`;
    fetch(url)
        .then(response=>{
            console.log(response);
            response.json();
        })
        .then(data={
            console.log(data);
        });
}

getAPI();

我希望当我输入"minuk\u test.html"时,html执行javascript文件.

但我有两个问题.

首先,我运行我的服务器.然后输入localhost:9999/Project/html/minuk\u test.html

其次,我在服务器打开的情况下运行javascript文件.

Response {
  size: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    stream: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    boundary: null,
    disturbed: false,
    error: null
  },
    type: 'default',
    url: 'http://127.0.0.1:9999/store/restaurant_info',
    status: 200,
    statusText: 'OK',
    headers: {
      connection: 'close',
      'content-length': '8035',
      'content-type': 'application/json; charset=utf-8',
      date: 'Mon, 30 May 2022 11:53:15 GMT',
      etag: 'W/"1f63-IYBGYq/MlY5TBn49Gp7cFQ7aH+A"',
      'x-powered-by': 'Express'
    },
    counter: 0,
    highWaterMark: 16384
  }
}

undefined //console.log(data);

回答大小为0.这正常吗?

but in postman, enter image description here

postman 可以接收json数据.

我不明白为什么我的html不能接收json.

推荐答案

因为html文件中没有包含javascript文件,也没有包含它,因为您没有在web服务器上提供静态文件,所以什么都不会运行(而且,它不是stylesheet,而是script标记)

如果您内联javascript,它应该可以工作.此外,在浏览器中,您在服务器端使用fetchnode-fetch):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API TEST</title>
    <script>
        function getAPI(){
            const url=`http://127.0.0.1:9999/store/restaurant_info`;
            fetch(url)
                .then(response=>{
                    console.log(response);
                    response.json();
                })
                .then(data={
                    console.log(data);
                });
        }

        getAPI();        
    </script>
</head>
<body>
    <h1>Test</h1>
    <div id="restaurant">
        <span></span>
        <span></span>
    </div>
</body>
</html>

但您应该设置静态文件,请参见此处:

https://expressjs.com/en/starter/static-files.html

此外,您可以设置自己的路由,无需扩展名,也可以使用.sendFile来提供特定文件,而不是fs,但您需要提供绝对路径(通过path模块):

请参见此处:

http://expressjs.com/en/api.html#res.sendFile

app.get('/my-route', function(request, response, next) {

    response.sendFile(require('path').join(__dirname, '../html/minuk_test.html'), function(err) {
        if (err) {
            next(err)
        } else {
            console.log('Sent:', fileName)
        }
    });
});

Mysql相关问答推荐

MySQL:返回所有条件(但不满足其他条件)为真的所有结果

如何通过SQL来计算到达特定值的行的数量

MySQL中的where语句会 destruct 全外连接.

带有 JOIN 和 WHERE 子句的 INSERT 语句

时间戳上滚动窗口的 SQL 计数不同

计算MySQL中的连续出现

MySQL - 如何查询涉及前面计算值的表结果

Mysql JSON_REMOVE 数组键和值 (MariaDB)

MySQL 将分组 JSON Select 转换为单个 JSON 对象

按年份范围 SQL 查询分组

MySQL:从 n 个关系表中 Select 所有具有 MAX() 值的行

基于 2 列的重复行的 SQL 查询

如何使用 sequelize 将复合主键放在连接表中?

Python MYSQL 更新语句

有什么方法可以显示`gunzip < database.sql.gz | 的进度? mysql ...`进程?

启用 NO_BACKSLASH_ESCAPES 选项时如何转义文字百分号?

如何将 mysqldump 的输出拆分为较小的文件?

在 MySQL 中存储 IPv6 地址

从另一个表中 Select 具有 id 的行

MySQL 的最大并发连接数