-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode-learn.js
More file actions
40 lines (31 loc) · 968 Bytes
/
node-learn.js
File metadata and controls
40 lines (31 loc) · 968 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const http = require('http');
const { URL } = require('url');
const user = {
id: 1,
name: 'Jan',
email: 'jan@example.com'
};
const products = [
{ id: 1, name: 'Product A', price: 29.99 },
{ id: 2, name: 'Product B', price: 49.99 },
{ id: 3, name: 'Product C', price: 19.99 }
];
const server = http.createServer((req, res) => {
const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
const pathname = parsedUrl.pathname;
if (req.method === 'GET' && pathname === '/user') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(user));
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found\n');
});
if (req.method === 'GET' && pathname === '/products') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(products));
return;
}
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});