@@ -129,6 +129,22 @@ void awesomeCallback(HTTPRequest * req, HTTPResponse * res) {
129
129
res->print (" </svg>" );
130
130
}
131
131
132
+ /* *
133
+ * This callback is configured to match all OPTIONS requests (see pattern configuration below)
134
+ *
135
+ * This allows to define headers there that are required to allow cross-domain-xhr-requests,
136
+ * which enabled a REST-API that can be used on the esp32, while the WebInterface is hosted
137
+ * somewhere else (on a host with more storage space to provide huge JS libraries etc.)
138
+ *
139
+ * An example use case would be an IoT dashboard that connects to a bunch of local esp32s,
140
+ * which provide data via their REST-interfaces that is aggregated in the dashboard.
141
+ */
142
+ void corsCallback (HTTPRequest * req, HTTPResponse * res) {
143
+ res->setHeader (" Access-Control-Allow-Methods" , " HEAD,GET,POST,DELETE,PUT,OPTIONS" );
144
+ res->setHeader (" Access-Control-Allow-Origin" , " *" );
145
+ res->setHeader (" Access-Control-Allow-Headers" , " *" );
146
+ }
147
+
132
148
/* *
133
149
* This callback will be registered as default callback. The default callback is used
134
150
* if no other node matches the request.
@@ -226,6 +242,14 @@ void serverTask(void *params) {
226
242
// the request, so this node can be accessed through https://myesp/
227
243
ResourceNode rootNode = ResourceNode (" /" , " GET" , &testCallback);
228
244
245
+ // As mentioned above, we want to answer all OPTIONS requests with a response that allows
246
+ // cross-domain XHR. To do so, we bind the corsCallback to match all options request
247
+ // (we can exploit the asterisk functionality for this. The callback is not required to
248
+ // process the parameters in any way.)
249
+ // Note the difference to the "/" in the rootNode above - "/" matches ONLY that specific
250
+ // resource, while slash and asterisk is more or less provides a catch all behavior
251
+ ResourceNode corsNode = ResourceNode (" /*" , " OPTIONS" , &corsCallback);
252
+
229
253
// The not found node will be used when no other node matches, and it's configured as
230
254
// defaultNode in the server.
231
255
// Note: Despite resource and method string have to be specified when a node is created,
@@ -243,6 +267,7 @@ void serverTask(void *params) {
243
267
server.registerNode (&faviconNode);
244
268
server.registerNode (&awesomeNode);
245
269
server.registerNode (&urlParamNode);
270
+ server.registerNode (&corsNode);
246
271
247
272
// The web server can be start()ed and stop()ed. When it's stopped, it will close its server port and
248
273
// all open connections and free the resources. Theoretically, it should be possible to run multiple
0 commit comments