javascript - 将 http 发送到 NodeJS/Express 后端以执行函数的按钮

标签 javascript html node.js http express

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

我尝试过不同的方法。当我提取 Philips 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();
});

最佳答案

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

测试/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>

关于javascript - 将 http 发送到 NodeJS/Express 后端以执行函数的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54414408/

相关文章:

html - IE中div定位问题

javascript - 用于 JavaScript 的简单所见即所得 BBCode 编辑器?

node.js 与 express 如何从 url 中删除查询字符串

javascript - 将 FormParams 与 Jersey 和 jQuery 结合使用

javascript - 我需要未填充属性值的 Mongoose/mongoDb 搜索

javascript - 通过单击 div 修改 url

javascript - 从网页获取所有图像并以编程方式保存到磁盘(NodeJS 和 Javascript)

node.js - 使用 JSBarCode 创建条形码

javascript - 强制 Chrome 始终获取 javascript 文件

javascript - IE8 getPrototypeOf 方法