ElectronicsESPTutorials/DIY

Setting Up a Node.js Server on ESP8266

Introduction

The ESP8266 is a low-cost Wi-Fi microcontroller that is widely used in IoT applications. One of its powerful capabilities is hosting a web server, allowing users to control devices remotely via a web interface. While most ESP8266 projects use Arduino IDE and embedded C programming, Node.js can also be used to create a lightweight server that communicates with the ESP8266. This article explains how to set up a Node.js server for controlling the ESP8266, sending and receiving data over Wi-Fi.

1. Understanding Node.js and ESP8266 Integration

Node.js is a JavaScript runtime that allows server-side programming. By setting up a Node.js server, you can interact with the ESP8266 through HTTP requests, WebSockets, or MQTT. This setup is useful for IoT applications that require remote monitoring and control.

Why Use Node.js with ESP8266?

  • Non-blocking I/O: Ideal for handling multiple concurrent requests.
  • WebSocket Support: Enables real-time communication with ESP8266.
  • RESTful API: Allows ESP8266 to send and receive HTTP requests easily.
  • Cross-Platform Compatibility: Works on Windows, Linux, and macOS.

2. Setting Up the Node.js Server

2.1 Installing Node.js and Required Packages

Before we proceed, ensure that Node.js and npm (Node Package Manager) are installed on your system.

Install Node.js (Linux & macOS)

curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs  # Ubuntu/Debian

Install Node.js (Windows)

Download and install from the official site: Node.js Download

Verify Installation

node -v  # Check Node.js version
npm -v   # Check npm version

2.2 Creating a Node.js Server

Create a new folder for your project:

mkdir esp8266_server && cd esp8266_server
npm init -y

Install Express.js, which simplifies server creation:

npm install express cors body-parser

Create an index.js file and add the following code:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

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

app.use(cors());
app.use(bodyParser.json());

let deviceStatus = { led: false };

// Route to get ESP8266 status
app.get('/status', (req, res) => {
  res.json(deviceStatus);
});

// Route to control ESP8266 LED
app.post('/led', (req, res) => {
  deviceStatus.led = req.body.state;
  console.log(`LED status: ${deviceStatus.led}`);
  res.json({ message: 'LED state updated', status: deviceStatus });
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

Run the server using:

node index.js

Your Node.js server is now running and ready to communicate with the ESP8266!

3. Configuring ESP8266 to Communicate with the Server

3.1 Setting Up ESP8266 with Arduino IDE

Ensure you have the ESP8266 board package installed in Arduino IDE. Then, create a new sketch and include the necessary libraries:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "Your_WiFi_SSID";
const char* password = "Your_WiFi_Password";
const char* serverAddress = "http://your-pc-ip:3000";

WiFiClient client;
HTTPClient http;

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("Connecting...");
    }
    Serial.println("Connected to WiFi");
}

void loop() {
    if (WiFi.status() == WL_CONNECTED) {
        http.begin(client, String(serverAddress) + "/status");
        int httpCode = http.GET();
        if (httpCode > 0) {
            String payload = http.getString();
            Serial.println("Server Response: " + payload);
        }
        http.end();
    }
    delay(5000); // Fetch data every 5 seconds
}

3.2 Sending Data to Node.js from ESP8266

Modify the loop function to send data:

void loop() {
    if (WiFi.status() == WL_CONNECTED) {
        http.begin(client, String(serverAddress) + "/led");
        http.addHeader("Content-Type", "application/json");
        String jsonPayload = "{\"state\": true}";
        int httpCode = http.POST(jsonPayload);
        if (httpCode > 0) {
            Serial.println("POST Sent: " + jsonPayload);
        }
        http.end();
    }
    delay(5000);
}

4. Testing and Deployment

4.1 Testing with Postman or Browser

  1. Open Postman or your browser and visit:
    http://your-pc-ip:3000/status
    

    You should see JSON output with the device status.

  2. To update the LED status, send a POST request to:
    http://your-pc-ip:3000/led
    

    With JSON body:

    { "state": true }
    

4.2 Deploying to a Cloud Server

You can host the Node.js server on Heroku, AWS, or a Raspberry Pi to make it accessible globally.

Conclusion

Setting up a Node.js server for ESP8266 allows seamless communication between devices over Wi-Fi. With this setup, you can build powerful IoT applications like remote monitoring, home automation, and smart sensor networks. By leveraging REST APIs and WebSockets, the ESP8266 can interact with cloud-based services, making it a robust choice for IoT development.

Read all article related to ESP: https://iotbyhvm.ooo/category/tutorials/iot-hardware/esp/

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *