user5109370
user5109370

Reputation:

Why my server crash when parsing json array?

I'm new to web development.

I'm learning: HTML, JavaScript, NodeJs, Ajax, Json. (I'm not familiar with jquery, and for now I want to professionalize with the list above).

I'm trying to send array to my nodeJs server and getting an error when parsing the data.

The client side:

<script type="text/javascript">

            var client = [
                            {"clientName":"", "clientNickName":  ""}
                         ];         
            }

            function onSubmit() {

                client[0].clientName = "AAA";
                client[0].clientNickName = "BBB";
                xmlhttp=new XMLHttpRequest();                   
                xmlhttp.open("POST","~/process_post",true);     
                xmlhttp.send(JSON.stringify(client));               
                return false;
            }

        </script>

The Server side:

var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/process_post', urlencodedParser, function (req, res) {   

   var Array1 = req.body.data;
   console.log("userName: " + Array1[0]);   
   res.sendFile( __dirname + "/" + "MyWeb.html" );
})

The crash is:

TypeError: Cannot read property '0' of undefined

It seems that the array is unknown ?

  1. How can I parse the array (at that point the array I'm sending has the size 1)

  2. when sending the data, Do I need to use:

    xmlhttp.send(JSON.stringify(client));

or:

xmlhttp.send(client);               

?

Thanks

Upvotes: 0

Views: 793

Answers (3)

ci_
ci_

Reputation: 8774

I'm assuming you use expressjs. Have a look at the docs: http://expressjs.com/api.html

Search for req.body:

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

So you would have to set up JSON parsing middleware like this :

var bodyParser = require('body-parser');

app.use(bodyParser.json());

Upvotes: 0

mscdex
mscdex

Reputation: 106696

You're missing the proper encoding and headers on the client side. Try this instead:

function onSubmit() {
  client[0].clientName = "AAA";
  client[0].clientNickName = "BBB";

  // properly encode the body
  var body = Object.keys(client).map(function(k) {
    return k + '=' + encodeURIComponent(client[k]);
  }).join('&');

  xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST","~/process_post",true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlhttp.send(body);
  return false;
}

OR you can keep the client-side code you currently have, but just add

xhr.setRequestHeader("Content-Type", "application/json");

and add/replace your body parsing middleware with

bodyParser.json()

Upvotes: 0

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

Your line here has an extra curly brace that is causing the JavaScript to be invalid and for it to parse incorrectly.

var client = [
                        {"clientName":"", "clientNickName":  ""}
                     ];         
        }

It needs to be this instead:

var client = [
                 {"clientName":"", "clientNickName":  ""}
             ];

Upvotes: 4

Related Questions