为什么我的客户端-服务器通信无法正常工作?

问题描述 投票:0回答:1

基本上,我试图从服务器端获取数据并在客户端使用它。这很简单,但我似乎错过了一些东西,因为它不起作用。

请参阅下面我在客户端的同一文件夹中名为index.html的文件的代码:

fetch('/lines', { method: 'GET', headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(linesOfGame => { console.log('SUCCESS') for (const line of linesOfGame) { const lines = document.querySelector('.lines') const newLine = document.createElement('div') newLine.textContent = line lines.appendChild(newLine) } })

请参阅下面我在服务器端的代码,位于同一文件夹中名为 script.js 的文件上:

`const express = require('express'); 常量应用程序 = Express(); app.listen(3000, () => console.log('在 3000 处监听'));

app.get('/lines', (req, res) => {
    console.log('SUCCESS')
    const linesOfGame =[' joseph', 'jacob', 'hart']
    res.json(linesOfGame);
});

`

我预计这会成功,但它似乎没有发送数组。 在服务器端没有出现错误。但是,在浏览器的控制台上显示“index.html:30 GET http://127.0.0.1:5500/lines 404(未找到)”。不知道在这里要做什么。任何帮助都会很棒。

json api express get client
1个回答
0
投票

您遇到的 404(未找到)错误通常表明客户端代码请求的 URL 未正确指向您的服务器。根据您的描述,您的服务器似乎在端口 3000 上运行,但您的客户端代码正在尝试访问不同端口 (5500) 上的资源,该端口可能对应于实时服务器工具用于提供静态服务的端口文件。

要解决此问题,您需要确保客户端获取请求针对服务器运行的正确端口。以下是调整代码的方法:

修改获取URL(客户端的index.html)以包含正确的服务器地址和端口(3000),如下所示:

<script>
fetch('http://localhost:3000/lines', { method: 'GET', headers: { 'Content-Type': 'application/json' } })
  .then(response => response.json())
  .then(linesOfGame => {
    console.log('SUCCESS');
    for (const line of linesOfGame) {
      const lines = document.querySelector('.lines');
      const newLine = document.createElement('div');
      newLine.textContent = line;
      lines.appendChild(newLine);
    }
  })
  .catch(error => console.error('Error:', error));
</script>

© www.soinside.com 2019 - 2024. All rights reserved.