![](/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.