node.js Error - throw new TypeError('first argument must be a string or Buffer');

后端 未结 1 1390
感动是毒
感动是毒 2021-01-11 16:16

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.


             


        
相关标签:
1条回答
  • 2021-01-11 16:37

    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 讨论(0)
提交回复
热议问题