Kreiranje servera bez biblioteke
Za kreiranje servera je potreban http/https objekat koji je ugradjen u core node.js-a te ga možemo importovati kao modul. Postoje dve opcije modula:
- http – Http je jedan od ugrađenih modula koji dolazi sa Node.js i omogućava kreiranje servera za prihvatanje zahteva od klijenta i vraćanje odgovora
- https – Https modul uključuje sve osnovne karakteristike http-a, ali sa dodatnim opcijama za rukovanje potrebnim bezbednosnim razlikama poput sertifikata.
Kada importujemo jedan od ova dva modula, on će nam vratiti “http/https” objekat, kao u sledećem primeru:
1 |
const http = require('http'); |
Sada kada imamo http objekat iskoristićemo ga za kreiranje servera koristeći metodu createServer():
1 |
const server = http.createServer() |
Da bi server započeo “osluškivanje” zahteva moramo ga startovati, to se radi pozivanjem metode listen():
1 |
listen(port, hostname, backlog, callback) |
Metoda listen() prihvata četri opciona parametra, a mi ćemo koristi samo prvi parametar koji definiše port:
1 2 3 |
const http = require('http'); const server = http.createServer() server.listen(3000); |
Zahtev ka serveru se upućuje sa ove adrese "http://localhost:3000". Za zaustavljanje rada server možemo korisiti njegovu metodu close().
Callback za reagovanje na zahtev tzv. requestListener()
U prethodnom primeru je kreiran server ali nema nikakvu funkcionalnost, da bi ovaj server ipak reagovao na neki zahtev potrebno je da mu se kreira neki event listener koji će osluškivati zahteve ka serveru. To možemo uraditi na standardni tzv. event-based način sa metodom on():
1 2 3 4 5 6 |
const http = require('http'); const server = http.createServer() server.on("request", (request, response) => { // handle requests }) server.listen(3000); |
Medjutim ovakav pristup se najčešće ne koristi (mada je potpuno validan), već se metodi createServer() kao parametar prosedjuje funkcija (tzv. requestListener()) koja reaguje na zahtev i koja sama automatski dodaje “request” event.
1 2 3 4 5 6 |
const http = require('http'); const requestListener = function(request, response) { // handle requests } const server = http.createServer(requestListener); server.listen(3000); |
zbog jednostavnosti najbolje je koristi anonimnu funkciju:
1 2 3 4 5 |
const http = require('http'); const server = http.createServer(function(request, response) { // handle requests }); server.listen(3000); |
Prihvatanje GET zahteva i odgovor
Prihvatanje zahteva
Uz zahtev serveru se šalje request objekat i njemu možemo da pristupimo kroz parametar “request”. To je prilično “veliki” objekat koji nosi puno informacija u svojim svojstvima i metodama, pa ih možemo iskoristi za sadržaj body-ja odgovora (npr. svojstva method, url, headers):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const http = require('http'); const server = http.createServer((request, response) => { let headers = request.headers; let method = request.method; let url = request.url; if (method === "GET" && url === "/") { console.log(request.url + "\n"); console.log(request.headers + "\n"); console.log(request); //hendle some response } } ) server.listen(3000); |
Parsiranje query-ja iz url adrese
Ukoliko je zahtev pošiljaoca specifičan on će ga proslediti kroz url (npr. http://host:8000/?name=Pera), te je stoga neophodno parsirati url i izvući podatke iz njega. Za parsiranje ćemo koristi node.js-ov modul “url”.
1 2 3 4 5 6 7 8 9 10 |
var http = require('http'); var url = require('url'); var server = http.createServer((request, response) => { var queryData = url.parse(request.url, true).query; //ukoliko u url-u (npr. http://host:8000/?name=Pera) postoji promenjiva "name" //možemo je izčupati iz url-a i kasnije iskoristi u odgovoru servera: var imeIzZahteva = queryData.name; }); server.listen(3000); |
Odgovor servera
a) API based odgovor
Za kreiranje osnovnog odgovora (response) ćemo koristi svojstva response objekata: statusCode i njegove metode: setHeader(), write() i end():
1 2 3 4 |
response.statusCode = 200 response.setHeader("Content-Type", "application/json") response.write("neki sadržaj body-ja") response.end() |
Za odgovor servera možemo iskoristi neke od podatak koje dobijamo iz request objekta:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Url zahteva = http://localhost:3000/" const http = require('http'); const server = http.createServer((request, response) => { let headers = request.headers; let method = request.method; let url = request.url; const responseBody = { headers, method, url, body: ["item1", "item2", "item3"] } if (method === "GET" && url === "/") { response.statusCode = 200 response.setHeader("Content-Type", "application/json") response.write(JSON.stringify(responseBody)) response.end() } } ) server.listen(3000); |
U prethodnom primeru je definisan najjednostavniji header odgovora, ovde možete pogledati kako može da izgleda standardni header.
NAPOMENA:
U prethodnom primeru možemo iskoristili prednosti koje donosi destrukturiranje objekta tako da veoma jednostavno kreiramo promenjive headers, method i url. Pogledajte ovde kako bi izgledao prethodni primer kada bi se koristilo destruktuiranje objekta, više o destrukturiranju objekta pogledajte u članku “Destruktuiranje u JavaScriptu”
b) HTML odgovor
U prethodnim primerima su odgovori (response) bili tzv. “API based”, ali ako hoćemo da vratimo html onda ćemo to uraditi slično sledećem primeru:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Url zahteva = http://localhost:3000/" const http = require('http'); const server = http.createServer((request, response) => { const { method, url } = request if (method === "GET" && url === "/") { response.setHeader("Content-Type", "text/html") response.statusCode = 200 response.end( `<!doctype html> <html> <body> <h2>Ovo je title</h2> <p>Ovo je neki tekst</p> </body> </html>` ) } } ) server.listen(3000); |
Ako je u prethodnom primeru url sa kojom pošiljalac šalje zahtev tipa http://localhost:3000/?name=Pera, onda će pošiljalac dobiti odgovor “Zdravo Pera” u suprotnom će dobiti odgovor “Hello World”.
Primanje podataka poslatih sa POST/PUT metodom
Pored get metode koja vidljivo šalje podatke u okviru url-a, možemo “nevidljivo” poslalti podatke serveru ukoliko koristimo POST metodu. Obično se ovaj metod koristi kada šaljemo prikupljene podatke iz forme. U ovome primeru formu ćemo generisati na serveru kada klijent pošalje zahtev za stranicu sa url-om: http://localhost:3000:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
const http = require('http'); const server = http.createServer((request, response) => { const { method, url } = request if (method === "GET" && url==="/") { response.setHeader("Content-Type", "text/html") response.statusCode = 200 response.end(`<!doctype html> <html> <body> <form action="/message" method="post"> <input type="text" name="fname" /><br /> <input type="number" name="age" /><br /> <input type="file" name="photo" /><br /> <button>Save</button> </form> </body> </html> `) } } ) server.listen(3000); |
Rezult ovog zahteva na klijentu ovako izgleda:
Kada korisnik unese podatke u formu i klikne na dugme “Save”, zbog definisanog HTML atributa “action” će se podaci iz forme poslati na stranicu sa url-om /message, i uz njega će se kreirati novi zahtev koji će proslediti podatke. Prikupljeni podaci iz forme se šalju kao “readable streams” i mogu izgledati ovako:
1 |
localefname=NekoIme&age=15&photo=naziv_izabrane_slike.png |
Šta su STREAMS?
Streams su način za efikasno rukovanje bilo kojom vrstom razmene informacija (koristi se takodje za čitanje/pisanje datoteka, mrežnom komunikacijom…). Streams nisu koncept jedinstven samo za Node.js, već postoje u okviru operativnog sistema Unix više decenija. Za razliku od tradicionalanog načina gde se datoteka cela učita u memoriju pa se tek onda obrađuje, ovde pri korišćenju streams program čita deo po deo podataka i simultano ga obrađuje, te na taj način uopšte ne opterećuje memoriju. Pored pomenute prednosti gde se efikasno koristi memorija jer ne trebate učitavati velike količine podataka u memoriju da biste mogli da ih obradite, postoji i druga prednost tzv. “vremenska efikasnost” koaj smanjuje potrebno vremena za početak obrade podataka, jer obradu možete započeti čim dobijete deo podataka, umesto da čekate da budu svi podaci budu dostupni. Pročitajte više o streams u članku Node.js Streams
Da bi znali u kome trenutku se šalju podaci i kada je prenos podataka završen za to postoje registrovani dogadjaji. “Readable streams” imaju registrovane sledeće tipove dogadjaja:
- data (ovaj dogadjaj se emituje kad god stream prosledi deo podataka tzv. “chunk”)
- end (ovaj dogadjaj se emituje kad god stream nema više podataka da prosledi)
- error
- close
- readable
U sledećem primeru ćemo se prijaviti na “data” dogadjaj za obaveštenje u kome trenutku se šalju podaci, a da bi smo znali kada je kraj poruke takodje se moramo prijaviti i na “end” dogodjaj:
1 2 3 4 5 6 7 8 9 10 11 |
if (req.method === 'POST' && url==="/message") { let body = ''; req.on('data', chunk => { // convert Buffer chunk to string body += chunk.toString(); }); req.on('end', () => { console.log(body); res.end('Preuzeli smo vaše poslate podatke'); }); } |
Promenjiva body bi po prijemu podataka mogla ovako izgledati:
1 |
fname=NekoIme&age=15&photo=naziv_izabrane_slike.png |
Kada imamo podatke u ovome obliku potrebno je da ih parsiramo, a za to ćemo koristi node.js-ov modul “querystring” i njegovu metodu parse() koja će podatke u ovom obliku prebaciti u kolekciju “key/value” parova:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const { parse } = require('querystring'); if (req.method === 'POST') { let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { console.log( parse(body) ); res.end('Preuzeli smo vaše poslate podatke'); }); } |
U konzoli će biti štampan sada nama čitljiv kod:
1 2 3 4 5 |
{ fname: 'NekoIme', age: '15', photo: 'naziv_izabrane_slike.png' } |
Ovde može te pogledati ceo prethodni primer objedinjen kao i primer u kome se concat-uje buffer (chunk) u niz.
Kreiranje servera sa Express bibliotekom
Express je minimalistički framework za Node.js koji pojednostavljuje proces kreiranja servera i rukovanja HTTP zahtevima. Da bismo započeli, prvo moramo instalirati Express pomoću npm:
1 |
npm install express |
Nakon što je Express instaliran, možemo ga importovati i koristiti za kreiranje servera. U sledećem primeru ćemo kreirati jednostavan server koji će odgovarati na GET zahtev:
1 2 3 4 5 6 7 8 9 10 11 |
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(Server is listening at http://localhost:${port}); }); |
U ovom primeru, Express aplikacija (app) koristi app.get() metodu za rukovanje GET zahtevima na osnovnom URL-u (“/”). Metoda res.send() šalje odgovor klijentu. Server se pokreće pomoću metode app.listen() koja osluškuje zahteve na definisanom portu (u ovom slučaju, 3000).
Prihvatanje POST zahteva i slanje odgovora
Pored GET zahteva, možemo koristiti Express za rukovanje POST zahtevima. U sledećem primeru, kreiraćemo rutu koja prihvata POST zahtev i šalje odgovor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const express = require('express'); const app = express(); const port = 3000; app.use(express.json()); // Middleware za parsiranje JSON podataka app.post('/data', (req, res) => { const data = req.body; res.json({ message: 'Data received', data }); }); app.listen(port, () => { console.log(Server is listening at http://localhost:${port}); }); |
Ovde koristimo app.use(express.json()) middleware za parsiranje JSON podataka iz tela zahteva. Kada klijent pošalje POST zahtev na “/data” rutu, server će prihvatiti podatke i poslati JSON odgovor nazad klijentu.
Dodavanje ruta i rukovanje greškama
Express omogućava lako dodavanje različitih ruta i rukovanje greškama. Na primer, možemo dodati rutu za “/about” i kreirati middleware za rukovanje 404 greškama:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.get('/about', (req, res) => { res.send('About page'); }); // Middleware za rukovanje 404 greškama app.use((req, res) => { res.status(404).send('Page not found'); }); app.listen(port, () => { console.log(Server is listening at http://localhost:${port}); }); |
Ovim pristupom, naš server može rukovati različitim rutama i vratiti odgovarajuće odgovore. Middleware za 404 greške se koristi za hvatanje svih nepostojećih ruta i slanje odgovarajuće poruke klijentu.
Express framework nudi mnogo više mogućnosti i fleksibilnosti, ali ovo su osnovni koraci za kreiranje jednostavnog servera. Više informacija možete pronaći u zvaničnoj dokumentaciji.
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 |
IncomingMessage { _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: [], flowing: null, ended: false, endEmitted: false, reading: false, sync: true, needReadable: false, emittedReadable: false, readableListening: false, resumeScheduled: false, errorEmitted: false, emitClose: true, autoDestroy: false, destroyed: false, errored: null, closed: false, closeEmitted: false, defaultEncoding: 'utf8', awaitDrainWriters: null, multiAwaitDrain: false, readingMore: true, decoder: null, encoding: null, [Symbol(kPaused)]: null }, _events: [Object: null prototype] { end: [Function: clearRequestTimeout] }, _eventsCount: 1, _maxListeners: undefined, socket: <ref *1> Socket { connecting: false, _hadError: false, _parent: null, _host: null, _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: [], flowing: true, ended: false, endEmitted: false, reading: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, errorEmitted: false, emitClose: false, autoDestroy: false, destroyed: false, errored: null, closed: false, closeEmitted: false, defaultEncoding: 'utf8', awaitDrainWriters: null, multiAwaitDrain: false, readingMore: false, decoder: null, encoding: null, [Symbol(kPaused)]: false }, _events: [Object: null prototype] { end: [Array], timeout: [Function: socketOnTimeout], data: [Function: bound socketOnData], error: [Function: socketOnError], close: [Array], drain: [Function: bound socketOnDrain], resume: [Function: onSocketResume], pause: [Function: onSocketPause] }, _eventsCount: 8, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, finalCalled: false, needDrain: false, ending: false, ended: false, finished: false, destroyed: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: true, bufferProcessing: false, onwrite: [Function: bound onwrite], writecb: null, writelen: 0, afterWriteTickInfo: null, buffered: [], bufferedIndex: 0, allBuffers: true, allNoop: true, pendingcb: 0, prefinished: false, errorEmitted: false, emitClose: false, autoDestroy: false, errored: null, closed: false, closeEmitted: false }, allowHalfOpen: true, _sockname: null, _pendingData: null, _pendingEncoding: '', server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, _connections: 2, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 0, keepAliveTimeout: 5000, maxHeadersCount: null, headersTimeout: 60000, requestTimeout: 0, _connectionKey: '6::::3000', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 2 }, _server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, _connections: 2, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 0, keepAliveTimeout: 5000, maxHeadersCount: null, headersTimeout: 60000, requestTimeout: 0, _connectionKey: '6::::3000', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 2 }, parser: HTTPParser { '0': [Function: bound setRequestTimeout], '1': [Function: parserOnHeaders], '2': [Function: parserOnHeadersComplete], '3': [Function: parserOnBody], '4': [Function: parserOnMessageComplete], '5': [Function: bound onParserExecute], '6': [Function: bound onParserTimeout], _headers: [], _url: '', socket: [Circular *1], incoming: [Circular *2], outgoing: null, maxHeaderPairs: 2000, _consumed: true, onIncoming: [Function: bound parserOnIncoming], [Symbol(resource_symbol)]: [HTTPServerAsyncResource] }, on: [Function: socketListenerWrap], addListener: [Function: socketListenerWrap], prependListener: [Function: socketListenerWrap], _paused: false, _httpMessage: ServerResponse { _events: [Object: null prototype], _eventsCount: 1, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: false, chunkedEncoding: false, shouldKeepAlive: true, _defaultKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedConnection: false, _removedContLen: false, _removedTE: false, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, socket: [Circular *1], _header: null, _keepAliveTimeout: 5000, _onPendingData: [Function: bound updateOutgoingData], _sent100: false, _expect_continue: false, [Symbol(kCapture)]: false, [Symbol(kNeedDrain)]: false, [Symbol(corked)]: 0, [Symbol(kOutHeaders)]: null }, [Symbol(async_id_symbol)]: 4, [Symbol(kHandle)]: TCP { reading: true, onconnection: null, _consumed: true, [Symbol(owner_symbol)]: [Circular *1] }, [Symbol(kSetNoDelay)]: false, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: null, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0, [Symbol(RequestTimeout)]: undefined }, httpVersionMajor: 1, httpVersionMinor: 1, httpVersion: '1.1', complete: false, headers: { host: 'localhost:3000', connection: 'keep-alive', 'cache-control': 'max-age=0', 'sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"', 'sec-ch-ua-mobile': '?0', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36', accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'sec-fetch-site': 'none', 'sec-fetch-mode': 'navigate', 'sec-fetch-user': '?1', 'sec-fetch-dest': 'document', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9,sh;q=0.8,sr;q=0.7,bs;q=0.6' }, rawHeaders: [ 'Host', 'localhost:3000', 'Connection', 'keep-alive', 'Cache-Control', 'max-age=0', 'sec-ch-ua', '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"', 'sec-ch-ua-mobile', '?0', 'Upgrade-Insecure-Requests', '1', 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36', 'Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Sec-Fetch-Site', 'none', 'Sec-Fetch-Mode', 'navigate', 'Sec-Fetch-User', '?1', 'Sec-Fetch-Dest', 'document', 'Accept-Encoding', 'gzip, deflate, br', 'Accept-Language', 'en-US,en;q=0.9,sh;q=0.8,sr;q=0.7,bs;q=0.6' ], trailers: {}, rawTrailers: [], aborted: false, upgrade: false, url: '/', method: 'GET', statusCode: null, statusMessage: null, client: <ref *1> Socket { connecting: false, _hadError: false, _parent: null, _host: null, _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: [], flowing: true, ended: false, endEmitted: false, reading: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, errorEmitted: false, emitClose: false, autoDestroy: false, destroyed: false, errored: null, closed: false, closeEmitted: false, defaultEncoding: 'utf8', awaitDrainWriters: null, multiAwaitDrain: false, readingMore: false, decoder: null, encoding: null, [Symbol(kPaused)]: false }, _events: [Object: null prototype] { end: [Array], timeout: [Function: socketOnTimeout], data: [Function: bound socketOnData], error: [Function: socketOnError], close: [Array], drain: [Function: bound socketOnDrain], resume: [Function: onSocketResume], pause: [Function: onSocketPause] }, _eventsCount: 8, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, finalCalled: false, needDrain: false, ending: false, ended: false, finished: false, destroyed: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: true, bufferProcessing: false, onwrite: [Function: bound onwrite], writecb: null, writelen: 0, afterWriteTickInfo: null, buffered: [], bufferedIndex: 0, allBuffers: true, allNoop: true, pendingcb: 0, prefinished: false, errorEmitted: false, emitClose: false, autoDestroy: false, errored: null, closed: false, closeEmitted: false }, allowHalfOpen: true, _sockname: null, _pendingData: null, _pendingEncoding: '', server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, _connections: 2, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 0, keepAliveTimeout: 5000, maxHeadersCount: null, headersTimeout: 60000, requestTimeout: 0, _connectionKey: '6::::3000', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 2 }, _server: Server { maxHeaderSize: undefined, insecureHTTPParser: undefined, _events: [Object: null prototype], _eventsCount: 2, _maxListeners: undefined, _connections: 2, _handle: [TCP], _usingWorkers: false, _workers: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 0, keepAliveTimeout: 5000, maxHeadersCount: null, headersTimeout: 60000, requestTimeout: 0, _connectionKey: '6::::3000', [Symbol(IncomingMessage)]: [Function: IncomingMessage], [Symbol(ServerResponse)]: [Function: ServerResponse], [Symbol(kCapture)]: false, [Symbol(async_id_symbol)]: 2 }, parser: HTTPParser { '0': [Function: bound setRequestTimeout], '1': [Function: parserOnHeaders], '2': [Function: parserOnHeadersComplete], '3': [Function: parserOnBody], '4': [Function: parserOnMessageComplete], '5': [Function: bound onParserExecute], '6': [Function: bound onParserTimeout], _headers: [], _url: '', socket: [Circular *1], incoming: [Circular *2], outgoing: null, maxHeaderPairs: 2000, _consumed: true, onIncoming: [Function: bound parserOnIncoming], [Symbol(resource_symbol)]: [HTTPServerAsyncResource] }, on: [Function: socketListenerWrap], addListener: [Function: socketListenerWrap], prependListener: [Function: socketListenerWrap], _paused: false, _httpMessage: ServerResponse { _events: [Object: null prototype], _eventsCount: 1, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: false, chunkedEncoding: false, shouldKeepAlive: true, _defaultKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedConnection: false, _removedContLen: false, _removedTE: false, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, socket: [Circular *1], _header: null, _keepAliveTimeout: 5000, _onPendingData: [Function: bound updateOutgoingData], _sent100: false, _expect_continue: false, [Symbol(kCapture)]: false, [Symbol(kNeedDrain)]: false, [Symbol(corked)]: 0, [Symbol(kOutHeaders)]: null }, [Symbol(async_id_symbol)]: 4, [Symbol(kHandle)]: TCP { reading: true, onconnection: null, _consumed: true, [Symbol(owner_symbol)]: [Circular *1] }, [Symbol(kSetNoDelay)]: false, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: null, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0, [Symbol(RequestTimeout)]: undefined }, _consuming: false, _dumped: false, [Symbol(kCapture)]: false, [Symbol(RequestTimeout)]: undefined } |
Destruktuiranje objekta request:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
const http = require('http'); const server = http.createServer((request, response) => { const { method, url, headers } = request; const responseBody = { headers, method, url, body: ["item1", "item2", "item3"] } if (request.method === "GET" && request.url === "/neki_slug") { response.statusCode = 200 response.setHeader("Content-Type", "application/json") response.write(JSON.stringify(responseBody)) response.end() } } ) server.listen(3000); |
Primer response header-a:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
200 OK Access-Control-Allow-Origin: * Connection: Keep-Alive Content-Encoding: gzip Content-Type: text/html; charset=utf-8 Date: Mon, 18 Jul 2016 16:06:00 GMT Etag: "c561c68d0ba92bbeb8b0f612a9199f722e3a621a" Keep-Alive: timeout=5, max=997 Last-Modified: Mon, 18 Jul 2016 02:36:04 GMT Server: Apache Set-Cookie: mykey=myvalue; expires=Mon, 17-Jul-2017 16:06:00 GMT; Max-Age=31449600; Path=/; secure Transfer-Encoding: chunked Vary: Cookie, Accept-Encoding X-Backend-Server: developer2.webapp.scl3.mozilla.com X-Cache-Info: not cacheable; meta data too large X-kuma-revision: 1085259 x-frame-options: DENY |
Primer concat-ovanja bufera
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 41 42 43 44 45 |
const http = require('http'); http.createServer((request, response) => { const { headers, method, url } = request; if (method === "GET") { response.setHeader("Content-Type", "text/html") response.statusCode = 200 response.end(`<!doctype html> <html> <body> <form action="/" method="post" _lpchecked="1"> <p>Unesi ime:</p> <input type="text" name="fname"><br> <p>Unesi godine:</p> <input type="number" name="age"><br> <p>Izaberi fotografiju:</p> <input type="file" name="photo"><br><br> <button>Save</button> </form> </body> </html> `) } if (request.method === 'POST') { let body = []; request.on('error', (err) => { console.error(err); }).on('data', (chunk) => { body.push(chunk); }).on('end', () => { //The concat() method joins all buffer objects in an array into one buffer object. body = Buffer.concat(body).toString(); response.on('error', (err) => { console.error(err); }); response.statusCode = 200; response.setHeader('Content-Type', 'application/json'); const responseBody = { headers, method, url, body }; // Note: the 2 lines below could be replaced with this next one: response.end(JSON.stringify(responseBody)) response.write(JSON.stringify(responseBody)); response.end(); }); } }).listen(3000); |
Primer
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 41 42 43 44 45 |
// Url početnog zahteva = http://localhost:3000" const http = require('http'); const { parse } = require('querystring'); const server = http.createServer((request, response) => { const { method, url } = request if (method === "GET" && url==="/") { response.setHeader("Content-Type", "text/html") response.statusCode = 200 return response.end(`<!doctype html> <html> <body> <form action="/message" method="post" _lpchecked="1"> <p>Unesi ime:</p> <input type="text" name="fname"><br> <p>Unesi godine:</p> <input type="number" name="age"><br> <p>Izaberi fotografiju:</p> <input type="file" name="photo"><br><br> <button>Save</button> </form> </body> </html> `) } if (method === 'POST' && url==="/message") { const FORM_URLENCODED = 'application/x-www-form-urlencoded'; if(request.headers['content-type'] === FORM_URLENCODED) { response.statusCode = 200; response.setHeader('Content-Type', 'application/json'); let body = ''; request.on('data', chunk => { body += chunk.toString(); }); request.on('end', () => { console.log( parse(body) ); return response.end('Preuzeli smo vaše poslate podatke'); }); } } } ) server.listen(3000); |