ERR_CONNECTION_REFUSED when communicating with my ESP8266 over WiFi

1.4k views Asked by At

Derived from the following code.

I uploaded that code to my ESP8266 and it's all good and okay when I communicate with it with my laptop while my laptop is connected to my network with a LAN cable.

The problem is: when I try to communicate with the ESP with my laptop or phone over Wi-Fi I get ERR_CONNECTION_REFUSED though they rarely work and communicate. I tried another phone another router, and did a factory reset to my router, and all the same.

I know that there is an option in the router that is called AP Isolation and it's been checked and it's disabled.

My question is: What could possibly be the reason for this error ERR_CONNECTION_REFUSED when I communicate with ESP8266 with that code?

If someone could help me I would be pleased as I am stuck in this situation.

The ESP code (same as the link):

#include <ESP8266WiFi.h>

const char* ssid = "*****";
const char* password = "*******";

WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.printf("Connecting to %s ", ssid);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");

  server.begin();
  Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());
}

// prepare a web page to be send to a client (web browser)
// the connection will be closed after completion of the response
// the page will be refreshed automatically every 5 sec
String prepareHtmlPage() {
  String htmlPage = String("HTTP/1.1 200 OK\r\n") +
                    "Content-Type: text/html\r\n" +
                    "Connection: close\r\n" +
                    "Refresh: 5\r\n" + "\r\n" +
                    "<!DOCTYPE HTML>" + "<html>" +
                    "Analog input:  " + String(analogRead(A0)) +
                    "</html>" + "\r\n";
  return htmlPage;
}


void loop() {
  WiFiClient client = server.available();

  // wait for a client (web browser) to connect 
  if (client) {
    Serial.println("\n[Client connected]");
    while (client.connected()) {
      // read line by line what the client (web browser) is requesting
      if (client.available()) {
        String line = client.readStringUntil('\r');
        Serial.print(line);
        // wait for end of client's request, that is marked with an empty line
        if (line.length() == 1 && line[0] == '\n') {
          client.println(prepareHtmlPage());
          break;
        }
      }
    }
    delay(1); // give the web browser time to receive the data

    // close the connection:
    client.stop();
    Serial.println("[Client disconnected]");
  }
}
1

There are 1 answers

2
Ashwini Shankar On

I hope its not too late and it helps someone in need. You need to do 2 things

Before WiFi.begin(), you need to add

WiFi.mode(WIFI_STA);

Second, you need to

#include <ESP8266mDNS.h>

in setup()

if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
}

and in loop()

MDNS.update();

Lastly, do not forget to add the following in every server response. Else, you will hit CORS error.

server.sendHeader("Access-Control-Allow-Origin", "*");

Please dont forget to add supporting libraries. Let me know if it works. Demo code would look like the below

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "<your SSID>";
const char* password = "<your WIFI Password>>";
int serverPort = 80;
int boardBaud = 115200;

ESP8266WebServer server(serverPort);

void handleRoot() {
  server.sendHeader("Access-Control-Allow-Origin", "*");
  server.send(200, "text/html", "<h1>Hello World</h1>");
}

void handleNotFound() {
  if (server.method() == HTTP_OPTIONS)
    {
        server.sendHeader("Access-Control-Allow-Origin", "*");
        server.sendHeader("Access-Control-Max-Age", "10000");
        server.sendHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS");
        server.sendHeader("Access-Control-Allow-Headers", "*");
        server.send(204);
    }
    else
    {
        server.send(404, "text/plain", "Error");
    }
}

void setup(void) {
  
  Serial.begin(boardBaud);
  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid, password);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  Serial.println("");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.onNotFound(handleNotFound);

  server.begin();
  
  Serial.println("HTTP server started");
}

void loop(void) {
  server.handleClient();
  MDNS.update();
}