Last active
November 25, 2021 15:08
-
-
Save Beyarz/b1d63a11f83efe8955f52e57bba7dc4d to your computer and use it in GitHub Desktop.
WEBrick::HTTPServlet::AbstractServlet with CORS enabled (works on Vercel with Ruby runtime)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rack' | |
require 'webrick' | |
require 'json' | |
Response = Struct.new(:status, :headers, :body) | |
app = Proc.new do |handler| | |
handler = Response.new | |
handler.status = 200 | |
handler.headers = { | |
'Content-Type' => 'application/json' | |
} | |
handler.body = [ | |
{'Message': 'Hello, world!'}.to_json | |
] | |
[handler.status, handler.headers, handler.body] | |
end | |
Rack::Handler::WEBrick.run app |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
Handler = Proc.new do |req, res| | |
coord = { | |
lat, | |
lon, | |
key | |
} | |
host = "https://api.openweathermap.org/data/2.5/onecall?lat=#{coord[:lat]}&lon=#{coord[:lon]}&appid=#{coord[:key]}" | |
uri = URI(host) | |
response = Net::HTTP.get(uri) | |
res.status = 200 | |
res['Content-Type'] = 'text/plain' | |
res.header['Access-Control-Allow-Origin'] = 'https://endpoint.domain' | |
res.header['Access-Control-Allow-Methods'] = 'GET' | |
res.header['Vary'] = 'Access-Control-Request-Headers' | |
res.header['Access-Control-Allow-Headers'] = 'Content-Type, Accept' | |
res.header['Access-Control-Request-Method'] = '*' | |
res['Access-Control-Allow-Credentials'] = true | |
res.body = response | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment