You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP32网页无法识别LittleFS上传的JavaScript文件问题求助

ESP32网页无法识别LittleFS上传的JavaScript文件问题求助

我正在做一个网页滑块功能,需要把滑块的值传回ESP32,逻辑上看起来都没问题,但网页就是识别不到我上传的JavaScript文件——浏览器控制台里明确提示找不到script2.js文件。

已找到修复方法:在Arduino代码中添加命令 server.serveStatic("/",LittleFS,"/");

我用LittleFS把JS文件上传到ESP32了,上传工具显示文件已经成功上传,但不管我把文件命名为script2.js还是script.js,网页都找不到它。奇怪的是,本地直接打开HTML文件的话,脚本是能正常识别并运行的,所以肯定不是文件名或者脚本本身的问题。我已经试了各种办法都没解决,把我的HTML、JS和Arduino代码贴在下面,希望能找到问题所在:

HTML代码

<!DOCTYPE html>
<html>

<head>
  <title>DASHBOARD</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="styles.css">
  <script src="node_modules\chart.js\dist\chart.umd.js"></script>
</head>

<body>
  <div class="topnav">
    <h1 id="header"> Pressure Waveform and Control Data</h1>
  </div>

  <div class="container">
    <canvas id="pressuregraph" width="800" height="400"></canvas>
  </div>
  <div class="slider-group">
    <div class="slider-container">
    <label for="pressureSlider">Pressure (cmH20)</label>
    <span id="pressliderValue">%SLIDERVALUE%</span>
      <input type="range" onchange="updateslider(this)" id="pressureSlider" min="0" max="50" value="%SLIDERVALUE%"
        step="1" class="slider">
    </div>
  </div>
  <button class="download-button">Download Data</button>
  <button class="user-manual">User Manual</button>

  <script src="script2.js"></script>

</body>

</html> 

JavaScript代码

window.addEventListener('load', getReadings);
 

function updateslider(element) {
    var sliderValue = document.getElementById("pressureSlider").value;
    document.getElementById("pressliderValue").innerHTML = sliderValue;
    console.log(sliderValue);
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/slider?value="+sliderValue, true);
    xhr.send();
} 
window.updateslider = updateslider;



const pressureData = [];

function updateChart(newValue) {
    pressureData.push(parseFloat(newValue)); // Ensure numerical values

    if (pressureData.length > 20) {
        pressureData.shift();
        pressureChart.data.labels.shift(); // Remove oldest label
    }

    // Update labels dynamically to match data points
    pressureChart.data.labels = pressureData.map((_, index) => index + 1);

    // Explicitly update the dataset reference
    pressureChart.data.datasets[0].data = [...pressureData];

    // Ensure Chart.js properly detects the update
    pressureChart.update('none');

}

const ctx = document.getElementById('pressuregraph').getContext('2d');
const pressureChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [],
        datasets: [{
            label: 'Pressure (cmH20)',
            data: [],
            borderColor: 'blue',
            borderWidth: 2,
            fill: false,
            tension: 0.2
        }]
    },
    options: {
        responsive: false,
        scales: {
            x: { title: { display: true, text: 'Data Points' } },
            y: { title: { display: true, text: 'Pressure (cmH20)' } }
        }
    }
});


function getReadings() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
        }
    };
    xhr.open("GET", "/readings", true);
    xhr.send();
}

if (!!window.EventSource) {
    var source = new EventSource('/events');

    source.addEventListener('open', function (e) {
        console.log("Events Connected");
    }, false);

    source.addEventListener('error', function (e) {
        if (e.target.readyState != EventSource.OPEN) {
            console.log("Events Disconnected");
        }
    }, false);

    source.addEventListener('pressure', function (e) {

        updateChart(e.data);
    }, false);
} 

Arduino代码

#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <LittleFS.h>
#include <Arduino_JSON.h>

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

AsyncWebServer server(80);
AsyncEventSource events("/events");

String sliderValue = "0";
const char* PARAM_INPUT = "value";
unsigned long lastTime = 0;
unsigned long timerDelay = 750;

String processor(const String& var){
  //Serial.println(var);
  if (var == "SLIDERVALUE"){
    return sliderValue;
  }
  return String();
}

void initLittleFS() {
  if (!LittleFS.begin()) {
    Serial.println("An error has occurred while mounting LittleFS");
  }
  else{
    Serial.println("LittleFS mounted successfully");
  }
}

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi ..");
  //Serial.println(cmH20)
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.println();
  initLittleFS();

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(LittleFS, "/index.html", "text/html");
  });

  server.on("/pressureslider", HTTP_GET, [] (AsyncWebServerRequest *request) {
    String inputMessage;
    // GET input1 value on <ESP_IP>/slider?value=<inputMessage>
    if (request->hasParam(PARAM_INPUT)) {
      inputMessage = request->getParam(PARAM_INPUT)->value();
      sliderValue = inputMessage;
    }
    else {
      inputMessage = "No message sent";
    }
    Serial.println(inputMessage);
    request->send(200, "text/plain", "OK");
  });

  server.on("/readings", HTTP_GET, [](AsyncWebServerRequest *request){
    String json = "sample";
    request->send(200, "application/json", json);
    json = String();
  });
  events.onConnect([](AsyncEventSourceClient *client){
    if(client->lastId()){
      Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
    }
    // send event with message "hello!", id current millis
    // and set reconnect delay to 1 second
    client->send("hello!", NULL, millis(), 10000);
  });
  server.addHandler(&events);

  // Start server
  server.begin();

}

void loop() {
  String pressuredata = "sample";
  if ((millis() - lastTime) > timerDelay) {
    // Send Events to the client with the Sensor Readings Every 10 seconds
    events.send("ping",NULL,millis());
    events.send(pressuredata.c_str(),"pressure",millis());
    lastTime = millis();
  }
  delay(100);
} 

补充说明:本地直接打开HTML文件时,浏览器控制台没有报错,脚本能正常加载并运行,说明脚本本身没有问题,问题应该出在ESP32的Web服务器配置上。

备注:内容来源于stack exchange,提问作者Agasthya Valluri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 03:44:32