Search code examples
vue.jssessionflaskflask-restplus

Why Flask doesn't persists sessions with VueJS `npm run serve` frontend?


I have a simple application with Flask and Rest-Plus on backend and VueJS frontend generated by VueCLI 3.

I am trying to set up sessions using Flask-Session but session variables saved in one request are not available in another.

I have tried lots of options but still got nothing.

Here is my vue.config.js:

module.exports = {
    devServer: {
        public: "localhost:8080",
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Allow-Headers": "Content-Type, Authorization, x-id, Content-Length, X-Requested-With",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
        },
        proxy: {
            '/api*': {
                // Forward frontend dev server request for /api to django dev server
                target: 'http://localhost:5000/'
            }
        }
    }
}

In my app.py I have set secret key and cors:

app.secret_key = "super_secret"
CORS(app, automatic_options=True, support_credentials=True)

Also, I have added decorators to my request handlers:

@cross_origin(supports_credentials=True)
def get(self):

And still nothing. In /login i set session['aaa']=1 and in another request i got KeyError.

I run frontend via npm run serve and backend via flask run. Any suggestions?


Solution

  • Solved by adding reverse proxy from flask. I've added it in my app.py so it passes all requests to frontend.

    If you will use this solution while development, don't forget to remove this endpoint before deploying to production server.

    @app.route('/dev', methods=['GET'])
    @app.route('/js/<path:dummy>', methods=['GET'])
    def proxy(dummy=None):
        if request.method == 'GET':
            resp = requests.get(request.base_url.replace('5000', '8080'))
            excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
            headers = [(name, value) for (name, value) in resp.raw.headers.items() if name.lower() not in excluded_headers]
            response = Response(resp.content, resp.status_code, headers)
        return response