How to add Access-Control-Allow-Origin headers to yaws file?

470 Views Asked by At

I send a post request to YAWS server using AJAX from a different port/domain but javascript returns this error message:

XMLHttpRequest cannot load http://0.0.0.0:8000/index.yaws. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

Now I understand that I need to include CORS headers in index.yaws file but I don't know how to do it in Erlang.

1

There are 1 best solutions below

1
On BEST ANSWER

If you want to set only localhost as an allowed origin you could try the code below. Note that it represents the JSON results you currently return with the variable YourJsonString.

out(Arg) ->
    Hdrs = yaws_api:arg_headers(Arg),
    case yaws_api:get_header(Hdrs, "Origin") of
        "localhost" ->
            [{header, {"Access-Control-Allow-Origin", "localhost"}},
             {html, YourJsonString}];
        _ ->
            {html, YourJsonString}
    end.