Skip to content

Instantly share code, notes, and snippets.

@webknjaz
Forked from zacknawrocki/coordinator.py
Last active August 25, 2019 20:35
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 webknjaz/a0c46a282958b1a747737872e32f5d81 to your computer and use it in GitHub Desktop.
Save webknjaz/a0c46a282958b1a747737872e32f5d81 to your computer and use it in GitHub Desktop.
CherryPy CORS issue
import cherrypy
import cherrypy_cors
class Coordinator:
@cherrypy.expose
def index(self):
return """<html>
<script type="text/javascript">
const id = 0
const title = 'sadf'
const start_time = '0'
const end_time = '12'
const userlist = ['x', 'y', 'z']
async function addMeeting() {
const data0 = {
id: id,
title: title,
start_time: start_time,
end_time: end_time,
userlist: userlist,
}
const data = JSON.stringify(data0)
try {
const resp = await fetch(
'http://localhost:3333/add_meeting',
{
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: data,
},
)
const json_resp = await resp.json()
console.log(json_resp)
} catch (e) {
console.warn('Exception: ' + e)
}
}
async function removeMeeting() {
const data0 = {id: id}
const data = JSON.stringify(data0)
try {
const resp = await fetch(
'http://localhost:3333/remove_meeting',
{
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: data,
},
)
const json_resp = await resp.json()
console.log(json_resp)
console.log('deleted')
} catch (e) {
console.warn('Exception: ' + e)
}
}
async function main() {
await addMeeting()
await removeMeeting()
}
main() // Entry point
</script>
</html>"""
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def add_meeting(self):
if cherrypy.request.method == 'OPTIONS':
cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])
result = {'operation': 'request', 'result': 'success'}
if cherrypy.request.method == 'POST':
result['data'] = cherrypy.request.json
return result
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def remove_meeting(self):
if cherrypy.request.method == 'OPTIONS':
cherrypy_cors.preflight(allowed_methods=['GET', 'POST'])
result = {'operation': 'request', 'result': 'success'}
if cherrypy.request.method == 'POST':
result['data'] = cherrypy.request.json
return result
def main():
cherrypy_cors.install()
cherrypy.config.update({
'server.socket_host': '127.0.0.1',
'server.socket_port': 3333,
'cors.expose.on': True,
})
cherrypy.quickstart(Coordinator())
__name__ == '__main__' and main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment