Acton
Acton

Reputation: 255

for a python flask web app deployed on heroku. how front end know dynamic backed server port?

The question could also be : how javascript get heroku env variable PORT?

I have a falsk web app. the backend server run like below

if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))

socketio.run(app, host='0.0.0.0', port=port)

my frontend client need to communicate with my server back and forth and I need to know which port backend is listenning.

In frontend index.html, i have below java script

socket = io.connect('0.0.0.0:5050'+ namespace);

My problem is, how do I know the dynamic port from backend?

I deployed my app on heroku, which i can't bind a fixed server. I have setted my heroku config var like

Config Vars
PORT: 5050

I thought every time my app is redeployed, this port would be grabbed and used but it isn't like that. Every time I re-deploy, server listening on a random port.

Can someone help, thank in advance.

Upvotes: 0

Views: 696

Answers (1)

Robert Moskal
Robert Moskal

Reputation: 22553

You can use the location object in the web client to find out everything you need to know about the server.

var HOST = location.origin.replace(/^http/, 'ws')
var ws =  io.connect(HOST + namespace);

However, in the documentation below they show the client side socket being initialized without arguments. Have you tried this?

 var socket = io();

I'm guessing using the "default constructor" accomplishes the same as the above: use the location and change the protocol.

Also they say you would enable session based affinity.

This is all from the heroku sockets docs https://devcenter.heroku.com/articles/node-websockets Though the article refers to a node based server, the principle the same with flask.

Upvotes: 1

Related Questions