Skip to content

Instantly share code, notes, and snippets.

@Beyarz
Last active November 25, 2021 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Beyarz/b1d63a11f83efe8955f52e57bba7dc4d to your computer and use it in GitHub Desktop.
Save Beyarz/b1d63a11f83efe8955f52e57bba7dc4d to your computer and use it in GitHub Desktop.
WEBrick::HTTPServlet::AbstractServlet with CORS enabled (works on Vercel with Ruby runtime)
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
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