Button to send http to NodeJS/Express backend to execute a function

I have a button in my frontend, and am using nodejs and express on my server-side backend. I have a function (essentially controlling Philips Hue API) on the backend, and I would like it to be executed when the button is clicked, through a http request.

I have tried different methods. the backend script for the Philips Hue controls work independently when i extract it and run it in git bash. I think there's some conceptual or coding errors on end.

Html Button

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

Client side 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);
    });
});

Backend/Server Side 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();
});


#javascript #html #node-js #express

6 Likes2.40 GEEK