【问题标题】:Button to send http to NodeJS/Express backend to execute a function将 http 发送到 NodeJS/Express 后端以执行功能的按钮
【发布时间】:2019-06-22 04:31:29
【问题描述】:

我的前端有一个按钮,并且在我的服务器端后端使用 nodejs 和 express。我在后端有一个函数(主要是控制 Philips Hue API),我希望在单击按钮时通过 http 请求执行它。

我尝试了不同的方法。飞利浦 Hue 控件的后端脚本在我提取它并在 git bash 中运行时独立工作。我认为最终存在一些概念或编码错误。

HTML 按钮

<button id="pulse" type="button" class="btn btn-danger">Pulsing Lights</button>

客户端JS

const pulseButton = document.getElementById("pulse");
pulseButton.addEventListener('click', function() {
  fetch('/huePulseLight', {method: 'POST'})
    .then(function(response) {
      if(response.ok) {
        console.log('Click was recorded');
        return;
      }
      throw new Error('Request failed.');
    })
    .catch(function(error) {
      console.log(error);
    });
});

后端/服务器端 JS

const port = 3000;
const server = http.Server(app);
server.listen(process.env.PORT || 3000, function(){
    console.log('Server running on port ' + port);
});


const app = express();

pulseLight = lightState.create().on().colorLoop();

function setPulseLight() {
  nodeHueapi.setLightState(1, pulseLight, function (err, lights) {
    if (err) throw err;
    displayResult(lights);
  });

  nodeHueapi.setLightState(2, pulseLight, function (err, lights) {
    if (err) throw err;
    displayResult(lights);
  });

  nodeHueapi.setLightState(3, pulseLight, function (err, lights) {
    if (err) throw err;
    displayResult(lights);
  });
}

app.post('/huePulseLight', function(req, res){
console.log("Pulse Light Set");
setPulseLight();
});

【问题讨论】:

  • 使用postman时api有响应吗?
  • 不。我认为端点还可以。我怀疑问题出在 http 调用上。

标签: javascript html node.js http express


【解决方案1】:

找出问题。在添加任何其他内容之前,请确保您的服务器和浏览器控制台都能正常通信。这或多或少是客户端和服务器通信的最少代码。在test 中运行node server.js,导航到localhost:3000,单击文本,观察控制台输出。

test/server.js

const express = require("express")
const app = express()

// make index.html accessible to clients
app.use(express.static('public'))

app.post('/huePulseLight', function(request, response){
  console.log("Pulse Light Set");
  response.send("Click Recorded")
});

app.listen(3000)

test/public/index.html

<html>
  <head></head>
  </body>
    <p id="pulse">foo</p>

    <script>      
      const pulseButton = document.getElementById("pulse")

      pulseButton.addEventListener('click', function() {
        fetch('/huePulseLight', {method: 'POST'})
          .then(response => response.text())
          .then(text => console.log(text))
      })
    </script>
  </body>
</html>

【讨论】:

  • 不,它没有。我认为 http 请求不正确,不胜感激。
【解决方案2】:

您的服务器上缺少app.listen(PORT)。

此外,您不会从服务器向客户端发送任何内容,这可能会导致客户端保持与服务器的连接打开,并且您的 fetch 承诺永远不会得到解决。

【讨论】:

  • 谢谢,前面有端口配置。只是不想泛滥。修改以反映。
  • 如果您在本地机器上的 3000 端口上运行服务器,您是否尝试过将 fetch URI 参数更改为 localhost:3000/huePulseLight
猜你喜欢
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多