如何解决使用fetch从ESP8266获取JSON响应
我创建了一个ESP8266 Web服务器,应在客户端请求时发送一个JSON对象。该服务器的代码如下:
#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
函数从我的JS代码中请求数据。但这会引发此错误:
Uncaught (in promise) SyntaxError: Unexpected end of input
at index.js:8
当我只是从浏览器连接到服务器的数据时,它会在页面上正确显示JSON对象。这是我要执行的代码:
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; dr
删除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));
要甚至在same-origin constraints上都使用它(除非代码段嵌入在esp8266.local服务的(HTML)资源中),服务器需要发送CORS标头。
server.on("/data",[]() {
Serial.println("Serving /data");
server.sendHeader("Access-Control-Allow-Origin","*");
server.send(200,"application/json","{\"key\": \"value\"}");
});
Goodie
headers: {'Content-Type': 'application/json'}
是没有意义的,因为Content-Type
是a response header。如果有的话,您将要使用'Accept' request header。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。