Files
kvida-os/components/transport/src/http_cors.h
Ronny Eia 3fee19c60a Replace form-urlencoded handlers with a JSON API + CORS
Both httpd servers now expose JSON endpoints (POST /api/wifi on the
commissioning AP; GET /api/status, GET/POST /api/mqtt on the settings
server) instead of form-urlencoded bodies, with CORS enabled
(http_cors.h) so a separately-hosted web app can call them from a
browser across origins -- not just the on-device pages, which now use
the same endpoints via fetch() too.

No JSON library ships with ESP-IDF v6.0.2 core (verified: no cJSON, no
bundled json component). Given these payloads are tiny, flat,
fixed-shape objects, json_helpers.h hand-rolls minimal strstr-based
extraction rather than adding a 4th external registry dependency
(already have mdns, mqtt, led_strip).

The settings page (mqtt.cpp) changes from server-side snprintf-built
dynamic HTML to a static embedded settings.html that fetches
/api/mqtt on load -- simpler code, and the actual point of the
refactor: the same API a future kvida-sdk client can use.

url_decode.h is removed (no longer needed once request bodies are
JSON instead of form-urlencoded).

Verified end-to-end against real hardware: /api/status, /api/mqtt,
and the CORS preflight for POST /api/mqtt all return correct
responses/headers when queried with a cross-origin Origin header.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-11 14:52:54 +02:00

25 lines
686 B
C++

#pragma once
#include "esp_http_server.h"
namespace kvida {
// Allows a separately-hosted web app (kvida-sdk, e.g. served from
// localhost:5173 via Vite during development) to call the device's JSON
// API from a browser across origins.
inline void add_cors_headers(httpd_req_t *req)
{
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
httpd_resp_set_hdr(req, "Access-Control-Allow-Methods", "GET, POST, OPTIONS");
httpd_resp_set_hdr(req, "Access-Control-Allow-Headers", "Content-Type");
}
inline esp_err_t cors_preflight_handler(httpd_req_t *req)
{
add_cors_headers(req);
httpd_resp_send(req, nullptr, 0);
return ESP_OK;
}
} // namespace kvida