• No results found

METHODS AND URLS

Obviously, when the user presses Enter, you want to display something different. You want to

process the form.

To that end, inspect the url property of the request object. The code for server.js should now

look like this:

require(‘http’).createServer(function (req, res) { if (‘/’ == req.url) {

res.writeHead(200, { ‘Content-Type’: ‘text/html’ }); res.end([

‘<form method=”POST” action=”/url”>’ , ‘<h1>My form</h1>’

, ‘<fieldset>’

, ‘<label>Personal information</label>’ , ‘<p>What is your name?</p>’

, ‘<input type=”text” name=”name”>’ , ‘<p><button>Submit</button></p>’ , ‘</form>’

].join(‘’));

} else if (‘/url’ == req.url) {

res.writeHead(200, { ‘Content-Type’: ‘text/html’ }); res.end(‘You sent a <em>’ + req.method + ‘</em> request’); }

98

PA R T I I • Essential Node APIs

If you go to the / URL, as shown in Figure 7-10, nothing changes.

Figure 7-10: The request handler still shows the same HTML when we go to the URL.

If you type in /url, you see something like Figure 7-11. The supplied URL matches the req. url in the else if clause, and the appropriate response is produced.

Figure 7-11: What you see when you go to /url as a result of req.url changing.

However, when you enter your name through the form, you see a message like that in Figure 7-12. The reason for this is that browsers will send the form data in the HTTP method specified in the action attribute of the <form> tag. The req.method value will be POST

C H A P T E R 7 • HTTP

99

Figure 7-12: In this case req.method is POST.

As you can see, you’re dealing with two different variables of the request: the URL and the method.

Node.JS puts in the url property everything that follows the hostname. If you navigate

to http://myhost.com/url?this+is+a+long+url, the contents of url are /url?this+is+a+long+url.

The reigning protocol of the web, HTTP/1.1 (as you may remember from the telnet

example in Chapter 6), establishes different methods for a request:

◾ GET (the default) ◾ POST

◾ PUT ◾ DELETE

◾ PATCH (the newest)

The idea behind this is that an HTTP client picks a method to alter a resource on a server, which is located by its URL, with certain data as the body of the request.

DATA

When you sent HTML, you had to define a Content-Type along with the body of your

response.

100

PA R T I I • Essential Node APIs

To process forms effectively, you absolutely need these two pieces of information. Just like the browser doesn’t know if the Hello World is going to be HTML or plain text unless you

explicitly indicate so, how do you know if the user is sending her name in JSON, XML, or plain text? The code for server.js should look like this now:

require(‘http’).createServer(function (req, res) { if (‘/’ == req.url) {

res.writeHead(200, { ‘Content-Type’: ‘text/html’ }); res.end([

‘<form method=”POST” action=”/url”>’ , ‘<h1>My form</h1>’

, ‘<fieldset>’

, ‘<label>Personal information</label>’ , ‘<p>What is your name?</p>’

, ‘<input type=”text” name=”name”>’ , ‘<p><button>Submit</button></p>’ , ‘</form>’

].join(‘’));

} else if (‘/url’ == req.url && ‘POST’ == req.method) { var body = ‘’;

req.on(‘data’, function (chunk) { body += chunk;

});

req.on(‘end’, function () {

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

res.end(‘<p>Content-Type: ‘ + req.headers[‘content-type’] + ‘</p>’ + ‘<p>Data:</p><pre>’ + body + ‘</pre>’);

}); }

}).listen(3000);

What is going on here? You are listening to the data and end events. You create a body

string that gets populated with different chunks, and then you consider that you have all the data only after the end events fires and not before.

The reason for this is that Node.JS allows you to process the data as it comes to the server. Because data can come in different TCP packets, it’s entirely possible that in real-world usage, you get a piece of the data first and sometime later you get the remainder.

C H A P T E R 7 • HTTP

101

Figure 7-13: In this example you output the Content-Type and request data back to the page.

For example, when you search on Google, the URL can look like that in Figure 7-14.

Figure 7-14: The highlighted part in the URL when a search is performed is q=<search term>.

Notice the fragment for the search in the URL gets encoded in the same way the form contents do. That’s why the Content-Type in this case is called urlencoded.

This particular fragment of URLs is also known as the query string.

Node.JS provides a module called querystring that makes it easy to parse those strings

into data you can easily access in the same way it does with headers. Create a file qs-exam- ple.js with the following contents and run it (see Figure 7-15).

console.log(require(‘querystring’).parse(‘name=Guillermo’)); console. log(require(‘querystring’).parse(‘q=guillermo+rauch’));

102

PA R T I I • Essential Node APIs

Figure 7-15: The output for the parse function calls.

As you can see, the querystring module is capable of taking a string and producing an

Object data-structure from it. This parsing process is homologous to Node taking the headers from the HTTP request data and producing the headers object you can easily access.

You’ll leverage the query string module to easily access the form field that’s submitted with the form.