set access cookies doesn't work flask vuejs
To set an access cookie in Flask and Vue.js, you can follow the steps outlined below:
Import the necessary modules: In your Flask application, you need to import the required modules. These typically include
flask
andflask_cors
for handling cross-origin resource sharing (CORS) if you're using Vue.js as a separate frontend.Initialize the Flask app: Create a Flask app instance using the
Flask
constructor. This instance will be used to configure and run your Flask application.Enable CORS: If you're using Vue.js as a separate frontend, you'll need to enable CORS to allow cross-origin requests. Use the
CORS
extension from theflask_cors
module to enable CORS in your Flask app.Set the access cookie: To set an access cookie, you can use the
set_cookie
method provided by the Flaskresponse
object. This method allows you to set a cookie with various parameters such as the cookie's name, value, expiration time, domain, and more.
```python from flask import Flask, Response from flask_cors import CORS
app = Flask(name) CORS(app)
@app.route('/') def index(): response = Response() response.set_cookie('access_token', value='your-access-token', max_age=3600, httponly=True) return response
if name == 'main': app.run() ```
In the above example, the set_cookie
method is used to set an access token cookie named 'access_token'
with a value of 'your-access-token'
. The max_age
parameter specifies the expiration time of the cookie in seconds, and httponly=True
ensures that the cookie is only accessible via HTTP requests and not through JavaScript.
- Access the cookie in Vue.js: In your Vue.js frontend, you can access the cookie using JavaScript. You can use the
document.cookie
property to retrieve the cookie value.
javascript
var access_token = document.cookie.replace(/(?:(?:^|.;\s)access_token\s\=\s([^;]).$)|^.*$/, "$1");
The above JavaScript code retrieves the value of the cookie named 'access_token'
and assigns it to the access_token
variable.
By following these steps, you should be able to set an access cookie in Flask and access it in your Vue.js frontend. Remember to customize the cookie parameters according to your specific requirements.