My backend runs in a docker container and my frontend runs in a different container and this is load balanced by traefik. I am unable to send the session created in the backed to the frontend.
my backend url - http://test-backend.localhost/api/test my frontend url - http://test-frontend.localhost/#/one
class Test(object):
exposed = True
@property
def db(self):
return cherrypy.request.db
@cherrypy.tools.accept(media='text/plain')
def GET(self):
cherrypy.session['something'] = "test"
return Service.get_service(self)
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def POST(self):
cherrypy.session['something'] = "john"
cookie = cherrypy.request.cookie
if 'uid' in cookie.keys():
uid = cookie['uid'].value
if 'uid' not in cookie.keys():
uid = 'uid' + datetime.datetime.utcnow().strftime("%Y%m%d%H%M%S")
cookie = cherrypy.response.cookie
cookie['uid'] = uid
cookie['uid']['expires'] = 3600
cookie['uid']['path'] = '/'
cookie['uid']['secure'] = True
# Manually set the session cookie in the response headers
cherrypy.response.headers['Set-Cookie'] = str(cookie)
input_json = cherrypy.request.json
print("session is", cherrypy.session.id)
print(input_json)
# Validate the Request JSON data
# try:
# schema = HitSchema()
# validated_data = schema.load(query_string)
# return Service.post_service(self, query_string, cherrypy.response.cookie)
# except ValidationError as e:
# cherrypy.response.status = 400
# return {"error": str(e)}
# Add the appropriate return statement here
return "POST request processed successfully"
def OPTIONS(self):
# Handle preflight request
cherrypy.response.headers['Access-Control-Allow-Credentials']
= 'true'
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
cherrypy.response.headers['Access-Control-Allow-Methods'] = 'GET, POST'
cherrypy.response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, Accept, X-Requested-With, Origin, Access-Control-Allow-Headers'
my frontend code looks like below.
const mutation = useMutation((newTodo: any) => {
return axios.post('http://test-backend.localhost/api/test', newTodo);
});
I tried like this as well
const mutation = useMutation((newTodo: any) => {
return axios.post('http://test-backend.localhost/api/hit', newTodo, {
withCredentials: true,
});
});
When I send a POST request from frontend to backend, session is created in the backend but cookie it not set in the browser.
when I try with credentials=true in firefox, I get the below error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘http://test-backend.localhost/api/test’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’)