Starting up the server

Now that we have defined our servers functionality, the only thing that's left to do is start it up:

     app.listen(3000, function(){
console.log('Server listening on port 3000');
});
  1. The listen method of app is called, which starts up the server and has it listen on port 3000 of the Pi.
  2. The first argument of listen is the port number we want to bind to.
  3. The second argument is a callback function that is called once the server has started. Inside this callback function we output a message to the console to indicate that the server is up and running.

All the code combined will give you the final server/index.js file:

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

app.get('/temperature', function(req, res) {
res.send('24 °C');
});

app.get('/humidity', function(req, res) {
res.send('48%');
});

app.listen(3000, function(){
console.log('Server listening on port 3000');
});

Push all code to the Pi, and from the root directory ( sensor-project), run the command:

node server

And you will see this output:

If you noticed, we ran only node server and not node server/index.js, which is where our code actually is. This is because when you specify a folder name without a filename, the node automatically looks for an index.js file by convention. If you named your file something else, say, index123.js, you would not be able to do this and would have to write the full location: node server/index123.js

Now, open a browser on any computer connected to the network and go to the address http://<raspbery_pis_ip_address>:3000/temperature, and you will get the response of 24 °C.


Similar is the case with http://<raspbery_pis_ip_address>:3000/humidity:


My Raspberry Pi's IP address, in this case, is 192.168.0.10.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.105.108