How can I parse parameters to a RESTful API - node.js

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)
})

Related

Axios - send get request with url + variable

This must be a stupid question, but I'm just starting and would appreciate any help!
So I have this code to get query parameter:
app.get('/', (req, res) => {
var code = req.query.code;
console.log(code);
And when I go to http://localhost:3000/?code=123, I get the code value in console, so it works fine.
Now, I need to send a GET request and add the value of the var code, this is where I'm stuck.
Let's say, I should send a GET request to 'http://testtesttest123.com/' + var code + 'hi'.
How can I do this?
I've tried this way and some other ways, but nothing worked:
axios.get('http://testtesttest123.com/?&code=', {params: {code}}, '&hi')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
});
Thank you in advance!
The axios.get call should look like this.
axios.get('http://testtesttest123.com/?code=' + code + '&hi')
With code = 123, this will call the URL http://testtesttest123.com/?code=123&hi.
Use the params config to send through query parameters. To support your empty hi parameter, you can include it in the URL string
axios.get("http://testtesttest123.com/?hi", {
params: { code }
})
For a code value of 123, this will perform a GET request to
http://testtesttest123.com/?hi&code=123
It will also ensure that the code value is made safe for use in URLs

Updating in Mongoose thru Postman

In my mongoose controller, I have something like:
exports.update_a_task = function(req, res) {
Task.findOneAndUpdate({_id: req.params.taskId}, req.body, {new: true}, function(err, task) {
if (err)
res.send(err);
res.json(task);
});
};
And in my PUT command in Postman I put:
url/doSomething/taskId/name //or ,name
But it would only prompt a CastError. How should the URL look like if I want to update a document using the PUT command?
if taskId and name are query params then url becomes
url/doSomething/?taskId=123&name=name
For this url: url/doSomething/taskId, you do something like this:
{
name: "the_name_you_want"
}
Inside of Postman.
To get it in mongoose you need to have the url like this
url/doSomething/:taskId/:name
then in postman you can do a put request to
url/doSomething/taskId/name
now you can use req.params.taskId
if you want to supply the data as /url/doSomething?taskId=&name= you would need to use
req.query.taskId

How to add id and body to axios.PUT request?

I am using axios with REACT and wondering how I can use it to make a put request to update an object through the backend node/express API I have set up.
I need to be able to pass an id and a body and not sure of how to do so.
axios.put('/api/profile', id, body)
.then(response => {
console.log(response.data);
})
.catch(err => {
console.log(err);
});
I do not think this will work as it takes the parameters of put(url, data, {headers})
The pattern for this is to making an axios request using the id of the entity/item that you want to update and return as shown:
axios.put(`/api/profile/${id}`, body); //using string interpolation
axios.put('/api/profile' + id, body); //using string concatenation
Then, on your express/node backend, you have a route that will match with this request's URI path and update that profile with the body. Not sure what you're using for your DB, but in pseudocode it would look like this:
/*
* 1. query profile Model for the specific profile
* 2. make sure to check if foundProfile is undefined or not.
* 3. update profile with body
* 4. Catch on errors
*/
router.put('/api/profile/:id', (req, res, next) => {
Profile.findbyId(req.params.id)
.then(foundProfile => foundProfile.update(req.body))
.catch(next);
})
As mentioned in a comment above, you could do this via the query string, but that would be odd/anti-pattern.

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.
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...");
}
});
});

Node+ElasticSearch: Sending a body on a GET request?

I am using Node.js and the request module to create a backend, and we've chose Elasticsearch as our data storage. All fine so far, except it seems Node doesn't support request bodies on GET requests? This is necessary for Elasticsearch's _search API, which expects only GET requests as part of their semantic design. Is there a solution to force Node to send the request body even in the cases of a GET request, or a mean to use _search on Elasticsearch with another HTTP verb?
function elasticGet(url, data) {
data = data || {};
return Q.nfcall(request.get, {
uri: url,
body: JSON.stringify(data) //<-- noop
}).then(function(response) {
return JSON.parse(response[1]);
}, function(err) {
console.log(err);
});
}
The _search API also accepts the POST verb.
For simplicity, why not use their api rather than manually making requests?
simple example:
var elasticsearch = require('elasticsearch'),
client = new elasticsearch.Client({
host: '127.0.0.1:9200',
log: 'trace'
});
client.search({
index: '[your index]',
q: 'simple query',
fields: ['field']
}, function (err, results) {
if (err) next(err);
var ids = []
if (results && results.hits && results.hits.hits) {
ids = results.hits.hits.map(function (h) {
return h._id;
})
}
searchHandler(ids, next)
})
You can combine it with fullscale labs elastic.js to build really complex queries, really fast.
https://github.com/fullscale/elastic.js
I had such an issue a few days ago.
tld;dr use POST
According to https://www.elastic.co/guide/en/elasticsearch/guide/current/_empty_search.html#get_vs_post you can also use POST with elastic.
I tried it with axios but it returns all data like with no body.
So I used POST instead. It works for me and I hope it will help to someone else.

Resources