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.
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:-
PUT request from POSTMAN:-
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...");
}
});
});
Related
So Am unable to make a search function i want to get a variable from search field and show the results that matched but am constantly getting this error
variable undefined when i try to console.log it in the node server
Edit-- i have already changed the axios.post to axios.get
app.get(`/search/`, (req, res) => {
let {name} =req.body
var Desc = name
console.log(name)
var Op= Desc+'%'
const q = "SELECT * FROM taric where Description LIKE ? ";
con.query(q,[Op], (err, search) => {
if (err) {
console.log(err);
return res.json(err);
}
console.log(search);
return res.json(search);
});
});
As you can see you are making POST request from frontend where as there is no POST request route to handle your request. As you have make route of GET for fetching the data from backend you need to make GET request from frontend as well. So you need to do as below:
axios.get(`your_endpoint_route_goes_here`);
instead of this:
axios.post(`your_endpoint_route_goes_here`, requestBodyObj);
HTTP methods are not the same.
You are using app.get in the server while triggering a POST call from your client.
axios.post <-----> app.get
(There is no route for POST call which client is expecting)
I am trying to make a basic RESTful API which works for the most part, but I would like to parse it url parameters such that I can apply multiple filters in one call
I have the following code:
app.get('/api/products/:id',(req, res) => {
let sql = "SELECT * FROM products WHERE id="+req.params.id;
let query = conn.query(sql, (err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
which I can use to apply one filter when I send a request like this:
localhost/api/products/1
but I would like to get all products with a name and their categories:
IE I would like to send a request like this:
localhost/api/products?name=stier&category=hammer
I would also like it to accept requests like this
localhost/api/products?category=hammer
Is that possible and how can I adapt my code to do that.
Thank you in advance
You can pass query parameters to that endpoint exactly as you mentioned. You can access those parameters using req.query
for: localhost/api/products?name=stier&category=hammer, req.query will contain:
{
name: 'stier',
category: 'hammer'
}
For that URL, you'll have to add a route for: /api/products and leave /api/products/:id for fetching a single product.
You need only to set '/api/products' the other part behind ? is called parameters and express puts them by itself on the object req.query
app.get('/api/products',(req, res) => {
console.log(req.query)
console.log(req.query.name)
console.log(req.query.category)
})
I have an express application with many routes that work fine but today I tried to add a new route and it just seems to no never get hit. I tried with a request from another application of mine and through Postman. Both return just Internal Server Error. However, every other one of my routes work just fine.
For the query in question test is a tinyint(1) and id is an int
Here is the route in question in my User.js route.
router.put("/add/:id", function (req, res, next) {
db.query(
"UPDATE user SET test = ? WHERE id = ?",
[1, req.params.id],
function (error, response) {
if (error) throw error;
if (response.affectedRows > 0) {
res.sendStatus(200);
} else {
res.sendStatus(500);
}
}
)
});
My postman request:
PUT http://localhost:3000/user/add/39583
Notthing gets hit though, I tried switching out put for post and I tried adding logging within the route but nothing shows. Not even the status is returned, it just says Internal Server Error in Postman
I've searched the web. I found a couple of things but I wasn't able to understand anything out.
I'm trying to send a get request from my angular to Node.js server. I want to send some search parameters for the my server. and it searches then returns the documents.
I'm tring this function to get send the request. But I don't know how to ad parameters beside this request.
GetCases(){
return this.http.get('/api/saleCases')
.map((response:Response)=>response.json());
}
In the server side
router.get('/saleCases', function(req, res){
console.log('get request for all cases');
Case.find({}).exec(function(err, cases){
if(err){
console.log("error retriving videos");
}else{
res.json(cases);
}
});
});
Can you help me to add the parameters in angular and read them in node.js? Or is there any kind of way that you can suggest me to use?
In Client side, first init your search parameters, something like:
const searchParams = {
params: {
param1: val1,
param2: val2,
...
}
}
then send your request to Server side like:
return this.http.get('/api/saleCases', searchParams)
In Server side you can access the params, using:
router.get('/saleCases', function(req, res){
const param1 = req.query.param1;
const param2 = req.query.param2;
});
I've been cobbling together code from a few different tutorials to build a basic todo app with the MEAN stack, using node, express, angular, and mongodb. One tutorial covered creating an api for GET, POST, and DELETE actions, but neglected the POST. So, I took it as a challenge to write a function that will update an existing todo. While I got the function working, I encountered an error involving req.params that I didn't understand.
Relevant Code:
Node:
In app.js
app.put('/api/todos/:_id', ngRoutes.update);
which leads to:
exports.update = function(req, res){
var user_id = req.cookies ?
req.cookies.user_id : undefined;
Todo.findByIdAndUpdate(req.params._id,
{ $set: {
updated_at : Date.now(),
content : req.body.formText
}}, function (err, todo) {
if (err)
res.send(err)
Todo.find({ user_id : user_id}, function(err, todos) {
if (err) res.send(err);
res.json(todos);
});
});
};
Angular:
$scope.update = function(id) {
$http.put('/api/todos/' + id, this.todo)
.success(function(data) {
console.log(data);
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
Jade/HTML:
form(ng-submit="update(todo._id)")
input.update-form(ng-show="todo.updating" type="text", name="content", ng-model="todo.formText" placeholder="{{todo.content}}")
This function works fine. It updates the todo in question, and returns the entire list to be reloaded onto the page with the updated value.
However, if in the node code, I change
content : req.body.formText
to
content : req.params.formText
I get the following error as my HTTP response:
Object {
message: "Cast to string failed for value "undefined" at path "content"",
name: "CastError",
type: "string",
path: "content" }
Even while, elsewhere in the function,
req.params._id
works fine to retrieve the todo's '_id' property and use it to find the appropriate document in the database. Furthermore, when viewing the request in Firefox's developer tools, the todo object appears in JSON format under the "Params" tab.
Why does this happen? What is the difference between using req.params vs req.body, and why does the second work and the first not?
req.params is for the route parameters, not your form data.
The only param you have in that route is _id:
app.put('/api/todos/:_id', ...)
From the docs:
req.params
This property is an object containing properties mapped to
the named route “parameters”. For example, if you have the route
/user/:name, then the “name” property is available as req.params.name.
This object defaults to {}.
source: http://expressjs.com/en/4x/api.html#req.params
req.body
Contains key-value pairs of data submitted in the request
body. By default, it is undefined, and is populated when you use
body-parsing middleware such as body-parser and multer.
source: http://expressjs.com/en/4x/api.html#req.body
req.params is the part you send in the request url parameter or the header part of requests.
req.params example in postman
In example above req.params is the data we are sending in postman after ninjas in the
url.
route.delete('/ninjas/:id',function(req,res,next)
{
Ninja.findByIdAndRemove({_id:req.params.id}).then(function(ninja)
{
console.log(ninja.toString());
res.send(ninja);
})
.catch(next);
});
req.body is the part you send in body part of requests
req.body example in postman
req.body is the JSON data we are sending in postman so we can access it in the post request body part.
route.post('/ninjas',function(req,res,next)
{
Ninja.create(req.body).then(function(ninja)
{
console.log("POST"+req.body);
res.send(ninja);
})
.catch(next);
});