Node.js: Set Cookie to 1 and Send POST Request
Here is an example code snippet to set a cookie to 1 using Node.js and send a POST request:
const http = require('http');
const server = http.createServer((req, res) => {
// Set cookie to 1
res.setHeader('Set-Cookie', 'myCookie=1');
// Send POST request
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
console.log(`POST request received with body: ${body}`);
res.end('POST request received');
});
} else {
res.end('Hello world!');
}
});
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});
This code creates a simple HTTP server that sets a cookie to 1 and sends a POST request if the incoming request method is POST. When the server receives a POST request, it logs the request body and sends a response. If the incoming request method is not POST, the server sends a 'Hello world!' response.
To test this code, you can use a tool like Postman to send a POST request to http://localhost:3000. The response should be 'POST request received'. You can also check the cookies in your browser's developer tools to verify that the cookie 'myCookie' is set to 1.
原文地址: https://www.cveoy.top/t/topic/njns 著作权归作者所有。请勿转载和采集!