0

I send ajax request:

var dataString = "{u:" + user + ", p:" + pa + "}"; 
            $.ajax({
                type: "POST",
                url: "lg.html",
                data: dataString,
                success: function(data){
                    if(data){
                        window.location = "http://localhost:8001/ea.html";  
                    }
                    else{
                        console.log(data);
                    }
                }
            });

Now, I have my server in node.js:

http.createServer(req).listen(8000);
function req(request, response){}

I want to get my form data attribute, so I do the next:

request.data;

but I see that req.data is undefined. How I can get my data attribute?

1 Answers1

1

With the http module alone, you're on your own for reading in and parsing the "data."

request is an IncomingMessage and Readable Stream, so you do this by binding to its 'data' and 'end' events.

function req(request, response) {
    var body = [];
    request.setEncoding('utf8');

    request.on('data', function (chunk) {
        body.push(chunk);
    });

    request.on('end', function () {
        var data;

        if (request.url === '/lg.html') {
            data = JSON.parse(body.join(''));

            var user = data.u;

            // ...
        }
    });
}

Alternatively, you can use a framework like express that can simplify this greatly:

var express = require('express');
var app = express();

app.use(express.bodyParser());

app.get('/lg.html', function (req, res) {
    var user = req.body.u;

    // ...
});

Though, if you're passing JSON as data:, you'll want to make sure it's formatted properly.

var dataString = JSON.stringify({ u: user, p: pa }); 

You should also set the contentType to match.

// ...
    data: dataString,
    contentType: 'application/json',
// ...

Or, give jQuery.ajax() the Object and let it URL-encode the data.

// ...
    data: { u: user, p: pa },
// ...
Community
  • 1
  • 1
Jonathan Lonowski
  • 112,514
  • 31
  • 189
  • 193