| 2 |
raymond |
1 |
// SPDX-License-Identifier: LGPL-3.0-or-later
|
|
|
2 |
// Copyright 2016-2026 Hristo Gochkov, Mathieu Carbou, Emil Muratov, Will Miles
|
|
|
3 |
|
|
|
4 |
//
|
|
|
5 |
// How to use CORS middleware
|
|
|
6 |
//
|
|
|
7 |
|
|
|
8 |
#include <Arduino.h>
|
|
|
9 |
#if defined(ESP32) || defined(LIBRETINY)
|
|
|
10 |
#include <AsyncTCP.h>
|
|
|
11 |
#include <WiFi.h>
|
|
|
12 |
#elif defined(ESP8266)
|
|
|
13 |
#include <ESP8266WiFi.h>
|
|
|
14 |
#include <ESPAsyncTCP.h>
|
|
|
15 |
#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
|
|
|
16 |
#include <RPAsyncTCP.h>
|
|
|
17 |
#include <WiFi.h>
|
|
|
18 |
#endif
|
|
|
19 |
|
|
|
20 |
#include <ESPAsyncWebServer.h>
|
|
|
21 |
|
|
|
22 |
static AsyncWebServer server(80);
|
|
|
23 |
static AsyncCorsMiddleware cors;
|
|
|
24 |
|
|
|
25 |
void setup() {
|
|
|
26 |
Serial.begin(115200);
|
|
|
27 |
|
|
|
28 |
#if ASYNCWEBSERVER_WIFI_SUPPORTED
|
|
|
29 |
WiFi.mode(WIFI_AP);
|
|
|
30 |
WiFi.softAP("esp-captive");
|
|
|
31 |
#endif
|
|
|
32 |
|
|
|
33 |
cors.setOrigin("http://192.168.4.1");
|
|
|
34 |
cors.setMethods("POST, GET, OPTIONS, DELETE");
|
|
|
35 |
cors.setHeaders("X-Custom-Header");
|
|
|
36 |
cors.setAllowCredentials(false);
|
|
|
37 |
cors.setMaxAge(600);
|
|
|
38 |
|
|
|
39 |
server.addMiddleware(&cors);
|
|
|
40 |
|
|
|
41 |
// Test CORS preflight request
|
|
|
42 |
// curl -v -X OPTIONS -H "origin: http://192.168.4.1" http://192.168.4.1/cors
|
|
|
43 |
//
|
|
|
44 |
// Test CORS request
|
|
|
45 |
// curl -v -H "origin: http://192.168.4.1" http://192.168.4.1/cors
|
|
|
46 |
//
|
|
|
47 |
// Test non-CORS request
|
|
|
48 |
// curl -v http://192.168.4.1/cors
|
|
|
49 |
//
|
|
|
50 |
server.on("/cors", HTTP_GET, [](AsyncWebServerRequest *request) {
|
|
|
51 |
request->send(200, "text/plain", "Hello, world!");
|
|
|
52 |
});
|
|
|
53 |
|
|
|
54 |
server.begin();
|
|
|
55 |
}
|
|
|
56 |
|
|
|
57 |
// not needed
|
|
|
58 |
void loop() {
|
|
|
59 |
delay(100);
|
|
|
60 |
}
|