Ariana Marta
Ariana Marta

Reputation: 11

Access-Control-Allow-Origin using PsychicHttp.h library for Arduino

I have a index.html file that send request to server. On the Arduino code I receive the request and i want to respond back to the webpage.

I get the following error on the browser: No 'Access-Control-Allow-Origin' header is present on the requested resource.

For what i have understood, the problem is that, when sending a request to the browser we have to "Access-Control-Allow-Origin " and one way to do it would be to add an Header to the response on the arduino for example: response->addHeader("Access-Control-Allow-Origin", "*"); request->send(response);

However, so far i didnt manage to find a way to add an header to the response using the PsychicHttp.h library.

So far i have this: server.on("/", HTTP_GET, [](PsychicRequest *request){ String output = "Hello world"; return request->reply(output.c_str()); });

Thank you for the help

Upvotes: 1

Views: 79

Answers (1)

John Hodge
John Hodge

Reputation: 1715

This feature doesn't seem to be well documented. In order to add the header you need to have a response object to add them to. Most of the example simply show sending a response directly from the request object. I was able to find an example showing how to build a response and from there was able to deduce how to add the headers.

Here's the example showing building a response: PsychicResponse example

What this boils down to is that in your request handler, instead of something like:

return request->reply(200, "text/plain", output.c_str());

you instead need to build a PsychicResponse and add the headers then send the response. So the handler then becomes:

PsychicResponse response(request);
response.addHeader("Access-Control-Allow-Headers", "access-control-allow-origin");
response.addHeader("Access-Control-Allow-Origin", "*");
response.setCode(200);
response.setContentType("text/plain");
response.setContent(output.c_str());

return response.send();

return resp.send();

Upvotes: 0

Related Questions