【问题标题】:Node server and client on different ports?不同端口上的节点服务器和客户端?
【发布时间】:2021-06-10 16:24:56
【问题描述】:

下面我的代码是通过我的 package.json 的单个调用运行的

const express = require('express');
const app = express();
const port = 3000;

//raspberryPI
//const dotenv = require('dotenv');
const { ChatClient } = require("dank-twitch-irc");
const { readPin } = require('./JavaScript/readPin');

const keywordsList = [];
*THIS IS A APP.USE FOR CORS, ONLY APPLICABLE IF I CAN GET THEM TO TALK IN THE FIRST PLACE*
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "http://localhost:3000"); // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res){
    res.sendFile(__dirname+'/views/index.html'); // change the path to your index.html
});

 app.get('/', (req, res) => {
  //res.sendFile(__dirname+'/views/index.html');  
  // res.writeHead(200, {
  //     'Connection': 'keep-alive',
  //     'Cache-Control': 'no-cache',
  //     'Content-Type': 'text/event-stream'
  //   });
  //   res.flushHeaders();
    const arrayToString = JSON.stringify(Object.assign({}, keywordsList))
    const stringToJsonObject = JSON.parse(arrayToString);
   

  res.send("data: " + arrayToString + "\n\n");

  //res.status(500).send({ error: 'something blew up' })
});
//app.use(express.static('views'))
//listen on port 3000
app.listen(port, () => console.info('Listening on port', { port }));

除此之外还有更多代码,但仅适用于以上代码

当我启动我的应用程序时,根据我放置静态 HTML 页面调用的位置(在第一个 GET res 之前或之后),我将在我的 localhost:3000 上启动并运行该页面,但我无法通过 express 连接它服务器或者我只是得到我推送到数组“keywordsList”但没有 HTML 页面的数据输出。每次我都会在控制台中遇到各种错误,如果需要,我可以显示这些错误。

通过在线阅读,我意识到我可能不明白我不能在同一个端口上同时为服务器和客户端提供服务并让它们相互通信。虽然这没关系,但网上没有太多关于如何修复它的解决方案。

我希望有人可以帮助我理解一些事情: 我是否正确地假设我需要将我的客户端和服务器保持在不同的端口上,以便它们能够正确地相互通信?如果是这样,有没有一种简单的方法可以在这里向我解释,或者我应该凭直觉去彻底检查我的项目的基本架构,以将客户端与服务器完全分开(我只是试图显示一个单独的 HTML页面会不断收到来自我的 API 的随机调用,所以我认为这有点多)。如果我不正确,我可以进一步解释我在浏览器中不断遇到的 GET 错误,但通常不是 404 app.js找到了。

对不起,代码有点混乱,随机评论。这是非常简单的,因为我来回尝试获取一个简单的 HTML 页面来加载数据,而服务器只是无法连接到客户端。

感谢您的任何反馈。

【问题讨论】:

    标签: node.js express xmlhttprequest webserver


    【解决方案1】:

    意识到我做错了什么。我不明白客户端需要在自己的本地服务器上(我的当前设置为 localhost:3000),然后实际的网络服务器需要在自己的端口上(localhost:8000)。然后,您需要将两者配置为通过代理相互通信,并可能解决 cors。

    不管怎样,我就是这样做的,我现在可以在页面上获取信息。只需要弄清楚如何构建有效载荷 lol

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-15
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多