如何解决托管网站加载了<body>中的错误,这些错误不在代码中
Ahoi,
我正在用“ Olimex ESP-32 POE”托管一个小型调试网站。目标是通过JSON发送一些内部数据,而不必使用Arduino IDE的串行输出(其原因无关紧要)。
#include "Arduino.h"
#include <WiFiClient.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
#include <string>
const char* ssid = "SSID";
const char* password = "password";
int looper = 0;
int looperSpeed = 0;
int looperMode = 0;
int looperDestination = 0;
int looperETC = 0;
WebServer webserver(80);
void initWebServer();
void getSettings() {
String response = "{";
response+= "\"speed\": \""+(String) looperSpeed+"\"";
response+= ",\"mode\": \""+(String) looperMode+"\"";
response+= ",\"dest\": \""+(String) looperDestination+"\"";
response+= ",\"etc\": \""+(String) looperETC+"\"";
if (webserver.arg("signalStrength")== "true"){
response+= ",\"signalStrengh\": \""+String(WiFi.RSSI())+"\"";
}
response+="}";
webserver.send(200,"text/json",response);
}
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += webserver.uri();
message += "\nMethod: ";
message += (webserver.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += webserver.args();
message += "\n";
for (uint8_t i = 0; i < webserver.args(); i++) {
message += " " + webserver.argName(i) + ": " + webserver.arg(i) + "\n";
}
webserver.send(404,"text/plain",message);
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid,password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
initWebServer();
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Set not found response
webserver.onNotFound(handleNotFound);
// Start server
webserver.begin();
Serial.println("HTTP server started");
}
void loop() {
webserver.handleClient();
//Some test values are changed here periodically (looperXYZ)
}
}
以及创建网站的部分:
std::string online_output = "Test";
const char* serverIndex() {
const char* o = online_output.c_str();
const char* r =
(std::string("") +
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>" +
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>" +
"<input type='file' name='update'>" +
"<input type='submit' value='Update'>" +
"</form>" +
"<div id='prg'>Progress: 0%</div>" +
"<div id='output' style=\"font-family: monospace; border: 1px solid black; width: 350px;min-height:398px;\">" +
"</div>" +
"<script>" +
"var id = 0;" +
"var removeId = 0;" +
"setInterval(function(){" +
/*"var xhReq = new XMLHttpRequest();" +
"xhReq.open('GET','/JSON',false);" +
"xhReq.send(null);" +
"var jsonObject = JSON.parse(xhReq.responseText);" +*/
"var data = {};" +
"$.ajax({" +
"type: 'GET'," +
"url: '/JSON'," +
"data: data," +
"async: true," +
"beforeSend: function (xhr) {" +
"if (xhr && xhr.overrideMimeType) {" +
"xhr.overrideMimeType('application/json;charset=utf-8');" +
"}" +
"}," +
"dataType: 'json'," +
"success: function (data) {" +
"document.getElementById('output').innerHTML = \"<p id=\" + id + \" style='margin:0;padding:0px;'>\" + \"Mode: \" + fill(data.mode,2) + \" | Speed: \" + fill(data.speed,4) + \" | Dest: \" + fill(data.dest,4) + \" | ETC: \" + fill(data.etc,5) + \"</p>\" + document.getElementById('output').innerHTML;" +
// "if (document.getElementById('output').offsetHeight > 400) document.getElementById('output').innerHTML = \"<p style='margin:0;padding:0px;'>\" + data.name + \"</p>\";" +
"if (document.getElementById('output').offsetHeight > 400) { document.getElementById(removeId).remove(); removeId++;}" +
"id++;" +
"console.log(data);" +
"}" +
"});" +
"},50);" +
"function fill(n,m) { " +
"var pre=\"\";" +
"var dec=10;" +
"for(var i=1;i<m;i++) { if(n<dec) { pre+=\".\"; } dec*=10; }" +
"pre = pre + n;" +
"return pre; }" +
"$('form').submit(function(e){" +
"e.preventDefault();" +
"var form = $('#upload_form')[0];" +
"var data = new FormData(form);" +
" $.ajax({" +
"url: '/update'," +
"type: 'POST'," +
"data: data," +
"contentType: false," +
"processData:false," +
"xhr: function() {" +
"var xhr = new window.XMLHttpRequest();" +
"xhr.upload.addEventListener('progress',function(evt) {" +
"if (evt.lengthComputable) {" +
"var per = evt.loaded / evt.total;" +
"$('#prg').html('progress: ' + Math.round(per*100) + '%');" +
"}" +
"},false);" +
"return xhr;" +
"}," +
"success:function(d,s) {" +
"console.log('success!')" +
"}," +
"error: function (a,b,c) {" +
"}" +
"});" +
"});" +
"</script>").c_str();
return r;
}
const char* host = "esp32";
void initWebServer() {
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */
webserver.on("/",HTTP_GET,[]() {
webserver.sendHeader("Connection","close");
webserver.send(200,"text/html",serverIndex());
});
webserver.on("/JSON",[]() {
getSettings();
});
/*handling uploading firmware file */
webserver.on("/update",HTTP_POST,(Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
},[]() {
HTTPUpload& upload = webserver.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n",upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf,upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n",upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
webserver.begin();
}
这是测试代码,因此以前的测试-FYI可能有剩余。
在加载网站时(当前我正在使用Chrome),有时可以正常工作,有时不加载任何内容(此网站无法正常工作,然后出现空白页面),有时我会收到类似xVºùÿý?øÿý?;">
的结果屏幕上唯一的输出。
详细显示以下内容:
<html><head></head><body>xV­ºùÿý?øÿý?;"><script>var id = 0; [...the rest of the <script> part is loaded properly...]
我刚刚注意到,在这些奇怪的字符前面有364个居中点(·),但是我实际上无法复制它们,除了Chrome-> Inspect->“ Sources” -Tab之外,没有任何编辑器显示它们。
因此,基本上,身体已经破裂,这些字符出现了,它们现在也不会改变。
有人可以指导我自己解决这个问题,以便始终正确加载网站或知道错误是什么吗?
解决方法
错误似乎在以下行:
const char* r = (std::string("") + “...”).c_str();
您正在创建std::string
,它在堆上分配了原始c字符串。然后,使用.c_str()
获得字符串的c表示形式。问题在于,由于尚未将字符串分配给类型为std::string
的变量,因此该字符串已释放。结果,您正在访问的不是您自己的内存。当它的内存还没有被重用时,它可以工作,但是want被另一个程序重用了,因为您从内存中获得了基本上随机的字节,所以它失败了。
您可以通过添加以下内容来解决该问题:
auto my_str = std::string("") + “...”;
因为您不需要原始指针。
对于服务器索引功能,它应类似于:
std::string serverIndex() {
对于您的初始化Web服务器功能:
webserver.on("/",HTTP_GET,[]() {
webserver.sendHeader("Connection","close");
auto r = serverIndex();
webserver.send(200,"text/html",r.c_str());
});
免责声明:此代码仅在应用中编写,因此未经测试。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。