![](/img/trans.png)
[英]Problem transferring a json string from the client to the esp8266 server
[英]Get a JSON response from ESP8266 using fetch
我創建了一個 ESP8266 web 服務器,它應該在客戶端請求時發送 JSON object。 該服務器的代碼如下所示:
#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();
}
然后我嘗試使用fetch
function 從我的 JS 代碼中請求數據。但它會拋出此錯誤:
Uncaught (in promise) SyntaxError: Unexpected end of input
at index.js:8
當我只是從瀏覽器連接到服務器的數據時,它會在頁面上正確顯示 JSON object。 這是我的代碼來做請求:
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));
tl;博士
刪除mode: 'no-cors'
並在草圖中添加server.sendHeader("Access-Control-Allow-Origin", "*")
。
獲取模式
mode: 'no-cors'
用於使用 Service Worker 進行緩存。
JavaScript 可能無法訪問結果響應的任何屬性
來源: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
因此,您告訴引擎將“無”轉換為 JSON,這反過來會導致“意外的輸入結束”。
替代解釋: https://stackoverflow.com/a/36303436/131929
使用這個修剪過的 JavaScript 片段; 它直接來自書本。
fetch('http://esp8266.local/data')
.then(response => response.json())
.then(data => console.log(data));
要在同源約束中使用它,除非代碼片段嵌入到 esp8266.local 提供的(HTML)資源中,否則服務器需要發送CORS header。
server.on("/data", []() {
Serial.println("Serving /data");
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "application/json", "{\"key\": \"value\"}");
});
好東西
headers: {'Content-Type': 'application/json'}
毫無意義,因為Content-Type
是響應header 。 如果您想要使用“接受”請求 header 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.