Sunday, August 6, 2017

[node.js][Resolved]First argument must be a string or Buffer TypeError: First argument must be a string or Buffer



Error message:
First argument must be a string or Buffer TypeError: First argument must be a string or Buffer
Reason :
What i wanted to do is throw a status code 201 and it fails if i use response.write() function, response.write accept the first argument in string or Buffer format only. I found i got some mistype, there is my source code:

function createItem(request, response){
    var id = counter += 1,
        item = request.body;
    todoList[id] = item;
    console.log("Create item",id, item);
    response.write(201,{
        "Content-type":"text/plain",
        "Location":"/todo/"+id}
        );
    response.end(item);
};
To do what a i want to do, throw a 201 page, i should use response.writeHead() but not response.write():
function createItem(request, response){
    var id = counter += 1,
        item = request.body;
    todoList[id] = item;
    console.log("Create item",id, item);
    response.writeHead(201,{
        "Content-type":"text/plain",
        "Location":"/todo/"+id}
        );
    response.end(item);
}; 
If you got some situation that you still want using response.write() method, you should convert the html status code from number to String format, such as :
function createItem(request, response){
    var id = counter += 1,
        item = request.body;
    todoList[id] = item;
    console.log("Create item",id, item);
    var statusCode = 201;
    response.write( statusCode.toString());
    response.end(item);
};

No comments :

Post a Comment