zdevita zdevita - 1 month ago 17
Node.js Question

Trouble adding item with PUT to dynamodb table: node.js aws-sdk

I am attempting to add an item to an existing dynamodb table using a PUT request. I have tried several variations of the code including using the .put as well as the .putItem functions. When I hard-code the url into the brower I get the following error:

Cannot GET /add-student?student_id=5&name=carl


When I cut the exact url which gave me this error and paste it into an api testing app, Postman, it works perfectly. I am well aware that the error says that I attempted a GET request, but I don't know what is wrong with my code.

Here's my code.

app.put('/add-student', function (req, res) {
var params = {
TableName : "student",

Item:{
"student_id" : {"N": req.query.student_id},
"name" : {"S": req.query.name}
}
}
dynamodb.putItem(params, function(err, data) {
if(err)
console.log(err);
else
console.log(JSON.stringify(data));
});
});


What might be causing this to be interpreted as a get request? Any help is much appreciated.

Answer

By default, when an URL is hit from the browser, the request will be send as HTTP GET request. You can't send other than GET request from browser directly without using plugins or tools.

This is the main reason for using tools like POSTMAN or any other plugins like Firefox plugins to test the REST services that works on different HTTP methods like POST, PUT etc.

1) I think when you hit the URL from POSTMAN, you would have selected the PUT method.

2) If you select the GET method in POSTMAN, you will get the same error.

See the screenshot below. Get request send from POSTMAN throws the same error.

GET request from POSTMAN:-

GET request from POSTMAN

PUT request from POSTMAN:-

PUT request from POSTMAN

Request send from browser:-

Request send from browser

My code is same as yours expect table name:-

app.put('/add-movie', function (req, res) {
    var params = {
        TableName:"Movies",
        Item:{
            "yearkey": {"N" : req.query.yearkey},
            "title": {"S" : req.query.title}

        }    
    };
    dynamodb.putItem(params, function(err, data) {
        if(err) {
            console.log(err);
            res.send("Put is failed...");
        }
        else {
            console.log(JSON.stringify(data));
            res.send("Put is successful...");
        }

    }); 
});