jeelabs / esp-link

esp8266 wifi-serial bridge, outbound TCP, and arduino/AVR/LPC/NXP programmer
Other
2.82k stars 720 forks source link

Support CORS for api endpoints #513

Open Sh4rK opened 3 years ago

Sh4rK commented 3 years ago

Hi,

We are trying to use a small device with esp-link on it as a serial-wifi bridge, but from a web application.

Currently, the requests to esp-link are blocked by the browser because of the same-origin policy. This can be bypassed using CORS headers, for example Access-Control-Allow-Origin can be used to allow a different origin to accept requests from the server.

To fix this in a very hacky way, (I think, correct me if I'm wrong) Access-Control-Allow-Origin: <urls> could be hardcoded with our specific URLs at https://github.com/jeelabs/esp-link/blob/cf329e8b84a55a05afa04df971d9abd9793c9130/web-server/web-server.c#L427

But to add it as a feature, I think it would need to be configurable, which I have no idea how to do (I have looked at the code for about 5 minutes so far).

My questions are:

uzi18 commented 3 years ago

It should be possible to implement, how long host field you need? Curious, What is your device you interface to?

uzi18 commented 3 years ago

In my own project have used * as url

Sh4rK commented 3 years ago

Our current origin URL would be 25 chars, but I think we should give some more, to make the feature more general. I don't know how long an average origin URL is, would 100 bytes be acceptable? I think that should be enough.

Using * would probably also be acceptable.

Curious, What is your device you interface to?

We're building a web app for small restaurants/food trucks/buffets to handle orders, and some of them want to use a scale to measure the food (price is proportional to weight). The scales we currently support use serial for communication.

uzi18 commented 3 years ago

Maybe could prepare test bin for you with this special header

Sh4rK commented 3 years ago

Thanks, that would be very helpful!

uzi18 commented 3 years ago

@Sh4rK try this (first you need 2x decompress it)

esp-link-v3.2.47.alpha.24-g74e2043-dirty-Lucjan.tgz.zip

uzi18 commented 3 years ago

@Sh4rK any update?

Sh4rK commented 3 years ago

@uzi18 sorry, we didn't get to it yet, but we'll definitely try.

Are the source changes for your build visible anywhere?

Sh4rK commented 3 years ago

@uzi18 We tried it, but it doesn't seem to work, the Access-Control-Allow-Origin header is not in the response. Do we have to turn it on somehow?

By the way, the route we would like to use from the web app is /console/text, this returns the serial data in JSON format.

uzi18 commented 3 years ago

@Sh4rK ok so now it is clear what api you need, so stay tuned

uzi18 commented 3 years ago

esp-link-v3.2.47.alpha.24-g74e2043-dirty-Lucjan.tgz.zip @Sh4rK try this one

Sh4rK commented 3 years ago

@uzi18 Thanks, that works! 🎉

Can you open a PR with the changes?