Tuesday, 14 March 2017

How to use nodejs server?

New to nodejs. Used to build web-based applications by ruby on rail, but hard to understand how a node server works.

1.postserver.js

 var http = require('http');
 var url = require('url');
 var querystring = require('querystring');

 var server = http.createServer(function (request, response) {
    if (request.method == 'POST') {
        var body = '';
        request.on('data', function (data) {
            body += data;

            if (body.length > 1e6) {
                response.writeHead(413,
                    {'Content-Type': 'text/plain'}).end();
                request.connection.destroy();
            }
        });
        request.on('end', function () {
            var POST = querystring.parse(body);
            console.log(POST);
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.end('Hello ' + POST.firstname + ' '+ POST.lastname + '\n');

        });
    }
});
server.listen(3000);

2.a simple form: form.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>form</title>
</head>
<body>
<h1>This is my form</h1>

<form action="http://localhost:3000/index.html" method="POST">
    First name:<br>
    <input type="text" name="firstname" value="default">
    <br>
    Last name:<br>
    <input type="text" name="lastname" value="default">
    <br><br>

    <input type="submit" value="Submit">
</form>
</body>
</html>

Need the answer for tasks below so that i can understand how it works:

modify form.html to query the fields of the database(submit and query data within html is easy here); modify postserver.js so to get the values from the form.



via runchu

No comments:

Post a Comment