In web development, setting cookies is a common task, primarily used to store user-related information such as preferences or session data. Here, I will introduce how to set cookie values in different environments.
1. Setting Cookies with JavaScript in the Browser
Setting cookies with JavaScript is relatively straightforward, as it can be done using the document.cookie property. A basic example of setting a cookie is provided below:
javascriptfunction setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } setCookie("user", "John Doe", 7); // Sets a cookie named 'user' with value 'John Doe' and expiration of 7 days
2. Setting Cookies on the Server Side Using Python (Flask Framework)
On the server side, setting cookies with Python's Flask framework can be done by using the set_cookie method on the response object. An example is as follows:
pythonfrom flask import Flask, make_response app = Flask(__name__) @app.route('/') def index(): resp = make_response("Setting a cookie") resp.set_cookie('username', 'John', max_age=60*60*24*7) # Sets cookie expiration to one week return resp if __name__ == "__main__": app.run()
3. Setting Cookies on the Server Side Using Node.js (Express Framework)
If you use Node.js with the Express framework, you can use the res.cookie() method to set cookies. The following is an example:
javascriptconst express = require('express'); const app = express(); app.get('/', function(req, res){ res.cookie('username', 'John', { maxAge: 900000, httpOnly: true }); res.send('Cookie is set'); }); app.listen(3000);
In the above example, we set a cookie named username with the value John, along with a maximum expiration time and the httpOnly attribute, which enhances security by preventing client-side scripts from accessing this cookie.
Conclusion
Setting cookies is an effective way to manage user sessions and personalized settings in web applications. Whether on the client side or server side, setting cookies is straightforward, but it is essential to prioritize security and user privacy.