Hi there,
for some weeks I'm trying to integrate a simple web server into my ESP8266 project, and it works fine (in principal) - files stored in /web in the LittleFS are transferred to the browser. (This is just an excerpt, the code is more complex in the real project.)
My problem: while HTML, js and even JSON files work perfectly fine and are interpreted by the browser, any kind of CSS files fail. The browser gets it, and when calling "/style.css" I see the CSS code, but the style is not applied to the layout.
Calling the same files (HTML, js, CSS) locally, the CSS works fine.
This is my code:
#include <ESP8266WiFi.h> // for general Wifi connection
#include <WiFiManager.h> // remembers known WiFi, easy config
#include <FS.h> // LittleFS filesystem
#include <LittleFS.h>
WiFiManager wifiManager;
WiFiServer server(80);
void handleHTTPrequest(WiFiClient client, String req) {
String filename = req.substring(5, req.indexOf(" ", 5));
File file = LittleFS.open("/web/" + filename, "r");
if (file) {
client.print(F("HTTP/1.1 200 OK\r\n"));
client.print(F("Content-Type: text/html\r\n"));
client.print(F("Connection: close\r\n\r\n"));
while (file.available()) {
String line = file.readStringUntil('\n');
client.print(line + "\n");
}
file.close();
Serial.println(F("HTTP file sent ...... ") + filename);
}
}
void setup() {
Serial.begin(115200);
delay(100);
LittleFS.begin();
String ssid = "ESP8266 webserver test " + String(ESP.getChipId());
if (wifiManager.autoConnect(ssid.c_str())) {
Serial.println(F("Wifi done."));
} else {
Serial.println(F("WiFi failed."));
}
server.begin();
Serial.println(F("webserver started."));
}
void loop() {
WiFiClient client = server.available();
if (client) { // new web session
client.setTimeout(5000);
String req = client.readStringUntil('\r');
while (client.available()) {
client.read(); // dump rest of request
}
handleHTTPrequest(client, req);
}
delay(50);
}
And this is the output on serial monitor:
11:45:16.517 -> HTTP file sent ...... index.html
11:45:17.589 -> HTTP file sent ...... style.css
11:45:17.729 -> HTTP file sent ...... script.js
11:45:17.822 -> HTTP file sent ...... readings
So the file is found and sent to the browser, but somehow ruined on the way.
This is the CSS code (but as stated, it works perfectly fine when opened locally):
html {
font-family: Arial, Helvetica, sans-serif;
display: inline-block;
text-align: center;
}
h1 {
font-size: 1.8rem;
color: white;
}
p {
font-size: 1.4rem;
}
.topnav {
overflow: hidden;
background-color: #0A1128;
}
body {
margin: 0;
}
.content {
padding: 5%;
}
.card-grid {
max-width: 1200px;
margin: 0 auto;
display: grid;
grid-gap: 2rem;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
.card {
background-color: white;
box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);
}
.card-title {
font-size: 1.2rem;
font-weight: bold;
color: #034078
}
Any ideas? Thank you!