简体   繁体   English

如何将 CORS-Header 添加到我的 esp32 网络服务器

[英]How to add CORS-Header to my esp32 webserver

I have the Problem that I cannot fetch() from my created.json because of an Access-Control-Allow-Origin Error.我有一个问题,由于访问控制允许来源错误,我无法从 created.json 中获取()。 I found out that I have to create some kind of a header, but I have no idea how such a command looks like with my used librarys and which parameters have to be selected.我发现我必须创建某种类型的 header,但我不知道这样的命令与我使用的库的外观以及必须选择哪些参数。 I hope you can help me with the needed addition to this code.我希望您能帮助我添加此代码所需的内容。

#include <ArduinoJson.h>
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>

#define DHTPIN 13
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

const char *ssid = "XXX";
const char *pwd = "XXX";

StaticJsonDocument<250> jsonDocument;
char buffer[250];

float temperature;
float humidity;

WebServer server(80);

void setup() {
dht.begin();
Serial.begin(9600);
Serial.println(WiFi.localIP());  
Serial.print("Connect to: ");
Serial.println(ssid);
WiFi.begin(ssid, pwd);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }
Serial.print("Connected. IP: ");
Serial.println(WiFi.localIP());
setup_routing();
}

void setup_routing(){
  server.on("/sensor", getEnv);
  sendHeader()
  server.begin();
}

void create_json(char *tag, float value, char *unit){
  jsonDocument.clear();
  jsonDocument["type"] = tag;
  jsonDocument["value"] = value;
  jsonDocument["unit"] = unit;
  serializeJson(jsonDocument, buffer);
}

void add_json_object(char *tag, float value, char *unit){
  JsonObject obj = jsonDocument.createNestedObject();
  obj["type"] = tag;
  obj["value"] = value;
  obj["unit"]  = unit;
}

void read_sensor_data(void * parameter) {
     for (;;) {
     temperature = dht.readTemperature();
     humidity = dht.readHumidity();
     }
     delay(2000);  
}

void getEnv() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  
  jsonDocument.clear();
  add_json_object("temperature", temperature, "°C");
  add_json_object("humidity", humidity, "%");
  
  serializeJson(jsonDocument, buffer);
  server.send(200, "application/json", buffer);
}

void loop() {
server.handleClient();
}

The fact is, you don't need to.事实是,你不需要。 The WebServer it self has API to automatically send CORS header. WebServer本身有API自动发送CORS header。 All you need to do is enable it in the setup.您需要做的就是在设置中启用它。 See example below:请参见下面的示例:

void setup_routing(){
  server.enableCORS(); //This is the magic
  server.on("/sensor", getEnv);
  server.begin();
}

Feel free to comment if this is not working.如果这不起作用,请随时发表评论。 I'll update my answer later.我稍后会更新我的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM