Node.js as Web-server: createServer(), writeHead() method; reading Query String, Split Query String

एक असली Node web server सवाल पढ़कर answer देता है: writeHead response को label करता है, req.url visitor की query string carry करता है, और url.parse(req.url, true).query इसे एक ready object में split करता है।

11 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Server जो कभी नहीं सुनता

आपके 5-line server में एक social flaw है: यह सबको वही बात कहता है। Schedule, seat count, या day 2 के events पूछिए: same greeting।

एक असली web server जवाब देने से पहले सवाल READ करता है। और सवाल, जो आप पहले से Unit 4 के GET lessons से जानते हैं, URL में travel करता है:

localhost:8080/?event=garba&day=2

? के बाद सब कुछ query string है, और आज server आख़िरकार इसे split करना और answer देना सीखता है।

Theory

writeHead: Body से पहले Label

res.writeHead(200, { 'Content-Type': 'text/html' });

एक response जो सबसे पहली चीज़ declare करता है: status code (200 OK, 404 Not Found: वही codes जो आपके AJAX guard ने check किए थे!) और headers, मुख्यतः Content-Type:

  • text/html: browser इसके बाद जो आता है उसे एक page की तरह render करता है
  • application/json: answer API data है: exactly वही जो एक AJAX caller का JSON.parse expect करता है

Order law: writeHead किसी भी write या end से पहले आता है: आप एक envelope को seal होने के बाद label नहीं कर सकते।

Theory

Query String को Split करना

/?event=garba&day=2 पर एक visit आपके callback में req.url के साथ लैंड होती है जिसमें exactly वह text है। आप इसे hand से split कर SAKTE हैं (? पर chop कीजिए, & पर split कीजिए, = पर split कीजिए), पर Node का built-in url module इसे properly करता है:

const q = url.parse(req.url, true).query;

  • url.parse(req.url, true) URL को dissect करता है; true query को एक parsed OBJECT की तरह माँगता है
  • इसका .query property फिर { event: 'garba', day: '2' } होता है

'2' पर quotes नोटिस कीजिए: query values strings की तरह आते हैं, अब तक के हर input जैसा वही convert-before-maths rule।

Practical

Server जो सवाल का Answer देता है

const http = require('http');
const url = require('url');

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });

    const q = url.parse(req.url, true).query;   // split the query string

    if (q.event == "garba") {
        res.write('<h1>Garba Night</h1>');
        res.write('<p>Day ' + q.day + ', Main Ground, 40 seats left</p>');
    } else {
        res.write('<p>Ask me with ?event=garba&day=2</p>');
    }
    res.end();
}).listen(8080);

// Visit:  localhost:8080/?event=garba&day=2
// Answer: Garba Night, Day 2, Main Ground, 40 seats left

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Quiz

Visitor localhost:8080/?event=garba&day=2 खोलता है। url.parse(req.url, true).query क्या return करता है?

  1. String "?event=garba&day=2", unchanged
  2. Object { event: 'garba', day: '2' }, values strings की तरह
  3. Object { event: 'garba', day: 2 }, day एक number की तरह
  4. एक array: ['garba', '2']
Show the answer

Object { event: 'garba', day: '2' }, values strings की तरह

true को second argument की तरह देने पर, parse query को parameter names से keyed एक ready object में split करता है: q.event और q.day बस काम करते हैं। Subtlety जो option C miss करता है: values हमेशा strings होती हैं: '2', 2 नहीं: URLs text carry करते हैं, तो q.day पर arithmetic को पहले parseInt चाहिए, वही lesson जो TextBoxes और InputBoxes ने सिखाया। Option A वह है जो req.url आपको parsing से PEHLE देता है (well, / prefix के साथ)। Option D names खो देता है, जो पूरा point हैं: parameters name से answer देते हैं, position से नहीं।

Think first

Full-Stack Loop बंद कीजिए

Unit 4 की live search ने xhr.open('GET', 'search.php?q=g') भेजा। अपने mind में server side rewrite कीजिए: यह Node server listing से अलग क्या करना चाहिए ताकि उस AJAX caller को serve कर सके: Content-Type और response format सोचिए, फिर tap कीजिए।

Show the answer

दो changes: writeHead application/json भेजता है (caller JSON.parse करेगा, render नहीं), और body एक JSON string बन जाती है: q.q वाले names containing events filter कीजिए, फिर res.end(JSON.stringify(matches))। Browser side जो आपने Unit 4 में लिखा उसे ZERO changes चाहिए: इसका responseText अब आपके SERVER से आता है। यही पूरा full stack है एक language में: AJAX engine पूछता है, event loop answer देता है, बीच में JSON: और आपने personally इस sentence का हर piece लिखा है।

Watch out

Web-Server Slips

write के बाद writeHead: headers body के बाद नहीं आ सकते: ERR_HTTP_HEADERS_SENT: हमेशा पहले label कीजिए।

Query Values पर Maths: q.day + 1 '21' territory है: पहले parseInt(q.day)।

Query को Blindly Trust करना: q.event missing हो सकता है (undefined) या nonsense: defensively branch कीजिए, जैसे listing का else करता है। हर visitor-supplied value एक guest है, family नहीं।

Theory

Subject का एक Lesson बाकी है

Server अब सुनता है, split करता है और answer देता है: पर यह अभी भी कुछ याद नहीं रखता: हर restart सारी registrations भूल जाता है। Finale Node को एक memory देता है: fs module: FILES को reading, creating, updating, deleting और renaming करना: registrations आख़िरकार disk पर लिखी जाती हैं, और FestConnect Live XML से लेकर एक persistent server तक complete होता है।

Summary

Key takeaways

  • writeHead(status, headers) response को किसी भी body से PEHLE label करता है: 200/404, और Content-Type text/html बनाम application/json।
  • Visitor की query string req.url में सवार होती है: /?event=garba&day=2।
  • url.parse(req.url, true).query इसे एक ready object में split करता है: q.event, q.day।
  • Query values strings हैं: arithmetic से पहले parseInt।
  • Query पर branch करके personally answer दीजिए; missing parameters के against guard कीजिए।
  • Content-Type को application/json + JSON.stringify में swap कीजिए, और यह server बिना बदले Unit 4 के AJAX को answer देता है।
  • Memory hook: envelope label कीजिए, सवाल split कीजिए, name से answer दीजिए।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Node.js

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Node.js as Web-server: createServer(), writeHead() method; reading Query String, Split Query String · Web Designing-2 (option A) · Gri-Learn