我想将数据从服务器传输到客户端JS文件,但是现在浏览器在其主屏幕上显示数据,就像我们使用innerHTML
property一样:
我检查了许多express.js教程,但似乎无法将数据发送(从技术上来说)到客户端js文件。
这是我正在寻找的图表:
[打开网页]-> [(在服务器中)从数据库获取数据]-> [将数据发送到客户端js文件] -> //在客户端进行更多操作
有解决此问题的提示吗?
这是我的代码:
// Makes display the client-side html, temporary disabled.
// app.use(express.static('client'));
// Queries
const QUERIES = {
prev: 'SELECT * FROM en.prevstore',
curr: 'SELECT * FROM en.currstore',
next: 'SELECT * FROM en.nextstore',
samp: 'SELECT * FROM en.sample'
}
// Create connection
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password123',
database: 'en'
});
// Router
app.use('/', (req, res) => {
db.query(QUERIES.samp, (err, results) => {
let ternary = err ? console.error(err) : res.json(results);
})
})
客户端HTML(来自注释的请求)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="quotes">
should be filled as quotes of data from database
</div>
<div class="color">
should be filled as color of data from database
</div>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
客户端JS:
function getWord() {
fetch('http://localhost:4000')
.then(res => res.json())
.then(({data}) => console.log(data))
}
getWord() // I know it won't work but tried for just in case.
当您尝试localhost:4000
在浏览器上加载时,它正在请求您的/
终结点。
您的服务器必须在此端点上返回您的静态文件(index.html&...)。
app.use(express.static('public'));
// public or any static directory containing your index.html, .js, images ...
然后,您可以将/
端点移至更明确的内容,例如/quotes
app.use('/quotes', (req, res) => {
db.query(QUERIES.samp, (err, results) => {
if (err) {
console.log('error', err);
res.status(500);
return res.end(); // closing the response /!\ IMPORTANT
}
res.json(results);
})
})
在您的客户端上,您将拥有类似的东西:
function getWord() {
fetch('http://localhost:4000/quotes')
.then(res => res.json())
.then(data => console.log(data))
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句