0

Could someone have any solution to solve this error?

I used Postman to add new student into students, but when it ran to req.on("data", function (chunk) {…}. It gave me the error which is like below.

create server or import library code which is like http, url,... I already wrote them in my code. The problem here is this function.

Thanks everyone due to watch my post.

function addStudent(req, res) {
    var body = "";

    req.on("data", function (chunk) {   // error from this line
        body += chunk;
    });

    req.on("end", function () {
        var post = url.parse("/?" + body, true);

        let name = post.query.name;
        let gender = post.query.gender;

        students.push({ name: name, gender: gender });
    });

    res.writeHead(200, { "Content-Type": "application/json" });
    return res.end({ success: "true" });
}
node:_http_outgoing:802
    throw new ERR_INVALID_ARG_TYPE(
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object
    at new NodeError (node:internal/errors:387:5)
    at write_ (node:_http_outgoing:802:11)
    at ServerResponse.end (node:_http_outgoing:934:5)
    at addStudent (D:\TDTU\Third_Year\HK1\Advanced_Web_Programming\Tasks\DAY2\520H0549\exercise3.js:27:13)
    at Server.<anonymous> (D:\TDTU\Third_Year\HK1\Advanced_Web_Programming\Tasks\DAY2\520H0549\exercise3.js:40:12)
    at Server.emit (node:events:513:28)
    at parserOnIncoming (node:_http_server:1013:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:117:17) {
  code: 'ERR_INVALID_ARG_TYPE'
}
Yoru
  • 1

1 Answers1

0

The error above shows that you're trying to assign an object to a string

In your case, you defined the var body to be a type of string, while in your callback function, an object was received.

to fix that, if you're unsure of the type of data/argument you'll be receiving in your callback, you can set the var body to be type any, like the code below;

    function addStudent(req, res) {
    var body = []; //this will set the data type to any, so you can push in any datatype/argument to it.

    req.on("data", function (chunk) {   // error from this line
        body.push(...chunk);
    });

    req.on("end", function () {
        var post = url.parse("/?" + body, true);

        let name = post.query.name;
        let gender = post.query.gender;

        students.push({ name: name, gender: gender });
    });
res.writeHead(200, { "Content-Type": "application/json" });
return res.end({ success: "true" });
}
Colorado Akpan
  • 306
  • 1
  • 12