Get a JSON response from ESP8266 using fetch
Posted: Tue Mar 22, 2022 11:15 pm
Hi
I've created a ESP8266 web server that should send a JSON object when it's requested by the client. The code of this server looks like this:
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266WiFi.h>
void setup() {
Serial.begin(115200);
WiFi.disconnect();
delay(10);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Successfully connected.");
Serial.println("\nGot IP: ");
Serial.print(WiFi.localIP());
if(MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/data", []() {
server.send(200, "application/json", "{\"key\": \"value\"}");
});
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
MDNS.update();
}
Then I am trying to request the data from my JS code using fetch function. But it throws this error:
Uncaught (in promise) SyntaxError: Unexpected end of input
at index.js:8
When I simply connect to the server's data from my browser it is correctly displayed the JSON object on the page. This is my code to do request:
fetch('http://192.168.1.135/data', {
method: 'GET',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(data => console.log(data));
I've created a ESP8266 web server that should send a JSON object when it's requested by the client. The code of this server looks like this:
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266WiFi.h>
void setup() {
Serial.begin(115200);
WiFi.disconnect();
delay(10);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Successfully connected.");
Serial.println("\nGot IP: ");
Serial.print(WiFi.localIP());
if(MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/data", []() {
server.send(200, "application/json", "{\"key\": \"value\"}");
});
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
MDNS.update();
}
Then I am trying to request the data from my JS code using fetch function. But it throws this error:
Uncaught (in promise) SyntaxError: Unexpected end of input
at index.js:8
When I simply connect to the server's data from my browser it is correctly displayed the JSON object on the page. This is my code to do request:
fetch('http://192.168.1.135/data', {
method: 'GET',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(data => console.log(data));