【问题标题】:How to transmit data to client-side js file from the server?如何将数据从服务器传输到客户端 js 文件?
【发布时间】:2020-01-22 09:38:15
【问题描述】:

我想将我的数据从服务器传输到客户端 JS 文件,但现在浏览器在其主屏幕上显示数据,就像我们使用 innerHTML 属性时一样:

我检查了一堆 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.

【问题讨论】:

  • 首先,你必须调用res.end()来关闭一个请求(如果你不使用res.json(...))。你能展示你的客户端代码吗?您想在第一个响应中注入数据(返回 html 和 js)还是公开返回 JSON 的 API 端点?
  • @Kornflexx 抱歉,我是后端的新手。我从来没有听说过这两种方式,所以我不能告诉你我到底想要什么。 (我在帖子中添加了 HTML 和 JS。)
  • 您正在使用端点:在客户端和服务器之间实现数据传输的非常常见的方式。

标签: javascript mysql database express


【解决方案1】:

当您尝试在浏览器上加载 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))
}

【讨论】:

  • 它在我的客户端开发面板上提供undefined。我只有 1 个服务器端口 (localhost:4000),我的依赖项是 express.js、cors.js 和 mysql。我错过了你的回答吗?
  • 我的错,我编辑了我的帖子。在开发工具的网络面板中可以看到服务器返回的json吗?
  • 是的,是的。使用localhost 和index.js。我可以在 Preview 面板上看到 json 数据。
  • 好的,我刚刚在客户端更改了承诺的最后一行,您现在应该可以访问数据了:)。
  • 甜蜜!你简直就是我的救命稻草。感谢您提供详细的解答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 2019-07-12
  • 2016-12-27
相关资源
最近更新 更多