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?

2
  • Shouldn't it be req.body, there is no data "attribute" anywhere? Commented Jul 28, 2013 at 11:24
  • @Bergi Express isn't used here. Though, it's a good suggestion. Commented Jul 28, 2013 at 11:25

1 Answer 1

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 },
// ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.