12

I'm trying to implement a basic addition program in node.js that accepts 2 numbers through the URL (GET Request) adds them together, and gives the result.


    var http = require("http");
    var url1  = require("url");

    http.createServer(function(request, response) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      var path = url1.parse(request.url).pathname;

      if(path == "/addition")
      {
        console.log("Request for add recieved\n");

        var urlObj = url1.parse(request.url, true);

        var number1 =  urlObj.query["var"]; 
        var number2 =  urlObj.query["var2"];
        var num3 = parseInt(number2);
        var num4 = parseInt(number1);

        var tot = num3 + num4;

        response.write(tot);
        response.write(number1 + number2);

      }
      else
      {
        response.write("Invalid Request\n");              
      }
      response.end();

    }).listen(8889);

      console.log("Server started.");

When I run, I'm getting 'Server started' message in the console. But when i request the url

`http://localhost:8889/addition?var=1&var2=20`

I'm getting the following error :

http.js:593 throw new TypeError('first argument must be a string or Buffer');

When I comment out the line that displays the variable 'tot', the code is running, and the output I get is the concatenated value of the 2 get parameters I pass. In this case, it happens to be 1+20 = 120. I'm not able to convert the data into numerical format.

Where is the mistake in the code? And what does the error message basically mean?

Many thanks in advance.

1
  • Note that the error message should also have included the text (assuming the code is saved as server.js): at Server.<anonymous> (server.js:21:18) which tells that the problem is on line 21. That helps find the problem quickly.
    – jjrv
    Commented May 6, 2012 at 12:38

1 Answer 1

14

You're passing numbers to response.write, when they should be strings. Like this:

response.write(total + '');

The variable total contains the number 21 because you passed the query parameters through parseInt() before summing. It will cause an error when sent through response.write unless you convert to a string first, by appending the empty string to it. number1+number2 is OK because they're strings, but their "sum" is "120".

I'd suggest also looking into the node.js package "express". It handles a lot of the basics for a HTTP server so you can write like:

var express=require('express');

var app=express.createServer();

app.get('/add',function(req,res) {
    var num1 = parseInt(req.query.var);
    var num2 = parseInt(req.query.var2);

    var total = num1 + num2;

    res.send(total + '');
});

app.listen(8888);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.