Chat freely about anything...

User avatar
By SuomyNonaPatri
#94052 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));
User avatar
By quackmore
#94133 the browser is working but fetch is not, I might be wrong but...

specifying "mode: 'no-cors'" as a fetch option may be tricky
you are telling fetch DON'T read data across origins, resulting in an empty response
then response.json() will fail on the empty response (line 8)

to verify if that's the case just log the response, I mean use console.log(response) instead of response.json()

to fix the issue, enable cors and add the following header to the ESP8266 response
Access-Control-Allow-Origin: *
User avatar
By Inq720
#94156 Is your primary-goal to study and build a web server that works with with json?
Or are you trying to get a server up so you can do some other project needing a GUI browser client?