그 결과를 html 사이트로 보내려면 creating an http server을 조사해야합니다.
var express = require('express');
var app = express();
app.use(express.static('public'))
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'db'
});
app.get('/rows', function (req, res) {
connection.connect();
connection.query('SELECT * FROM users', function(err, rows, fields)
{
connection.end();
if (err) throw err;
res.json(rows);
});
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
이 파일을 실행하면 컴퓨터의 포트 3000에 서버가 만들어집니다.
프로젝트에서 루트 수준에 public
디렉터리를 만듭니다.
<html>
<head>
<title>My db rows</title>
</head>
<body>
<div id="table"></div>
<script type="text/javascript">
var opts = {
url: 'http://localhost:3000/rows/'
};
fetch(opts)
.then((res) => {
if (res.ok) {
return res.json();
}
})
.then((rows) => {
for (let row of rows) {
// row will be a mysql row -- you can loop over these and do what you want with them
}
})
.catch(console.log);
</script>
</body>
</html>
주 : 거기에서 당신은 다음과 같은 뭔가 index.html
라는 파일을 만들 수 있습니다 내 요청을 실행하기 위해 새로운 가져 오기 API를 사용하고,하지만 당신은 쉽게 JQuery와 또는 XHR를 사용할 수 있습니다. 패치 API는 here으로 자세히 설명 할 수 있습니다.
그런 다음 브라우저에서 http://localhost:3000/index.html
으로 이동하여 결과를 확인하십시오.