[英]Get a JSON response from ESP8266 using fetch
I've created a ESP8266 web server that should send a JSON object when it's requested by the client.我创建了一个 ESP8266 web 服务器,它应该在客户端请求时发送 JSON object。 The code of this server looks like this:
该服务器的代码如下所示:
#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();
}
Then I am trying to request the data from my JS code using fetch
function. But it throws this error:然后我尝试使用
fetch
function 从我的 JS 代码中请求数据。但它会抛出此错误:
Uncaught (in promise) SyntaxError: Unexpected end of input
at index.js:8
When I simply connect to the server's data from my browser it is correctly displayed the JSON object on the page.当我只是从浏览器连接到服务器的数据时,它会在页面上正确显示 JSON object。 This is my code to do request:
这是我的代码来做请求:
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 tl;博士
Remove mode: 'no-cors'
and add server.sendHeader("Access-Control-Allow-Origin", "*")
in the sketch.删除
mode: 'no-cors'
并在草图中添加server.sendHeader("Access-Control-Allow-Origin", "*")
。
Fetch modes获取模式
mode: 'no-cors'
is intended for caching with Service Workers. mode: 'no-cors'
用于使用 Service Worker 进行缓存。
JavaScript may not access any properties of the resulting Response
JavaScript 可能无法访问结果响应的任何属性
source: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode来源: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
Hence, you are telling the engine to convert "nothing" to JSON which in turn leads to "Unexpected end of input".因此,您告诉引擎将“无”转换为 JSON,这反过来会导致“意外的输入结束”。
Alternative explanation: https://stackoverflow.com/a/36303436/131929替代解释: https://stackoverflow.com/a/36303436/131929
Use this trimmed JavaScript snippet;使用这个修剪过的 JavaScript 片段; it's straight from the book.
它直接来自书本。
fetch('http://esp8266.local/data')
.then(response => response.json())
.then(data => console.log(data));
To use this even across the same-origin constraints , which apply unless the snippet is embedded in a (HTML) resource served by esp8266.local, the server needs to send a CORS header.要在同源约束中使用它,除非代码片段嵌入到 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\"}");
});
Goodie好东西
headers: {'Content-Type': 'application/json'}
is pointless because Content-Type
is a response header . headers: {'Content-Type': 'application/json'}
毫无意义,因为Content-Type
是响应header 。 If at all you will want to use the 'Accept' request header .如果您想要使用“接受”请求 header 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.