I am working on CompoundJS and i would like to create an api for my mobile application.
Below is the expected output
1) An api localhost:3000/test
2) Some data has tobe POSTED to this api say number: 1
3) The API should respond with the number posted, result should be = 1
I tried the below
1) Created a controller say test_controller.js
2) Added an action showtest with below code
action(function showtest(req, res) {
console.log(req.body);
});
3) Added router config like
map.post('test', 'test#showtest')
When i posted to the url localhost:3000/test, it shows
like 200 successful, but in Firebug console the response shows error.
What am i doing wrong? is there anything as like Rails render :text => "hello"
we can use it for CompoundJS.
Your action isn't correct. Try this:
action('showtest', function() {
for (var key in req.body)
{
send(key.toString());
break;
}
});
Express used to expose a .rawBody property on the request object, which would contain the raw data posted, but as of Express 3.x this functionality has been removed. The for loop in the above code will return the first key of the req.body object (which, when the data POST'ed is just a single number, will be that number).
Related
Here In my mongo collection I have few records. I am writing an API in node js where I pass the ID in request body. My API have to take ID from request body and need to fetch it's whole records in response. but I am getting empty array.
My mongo collection record:
[{ accountId:"a1",name:"test"}]
My Node js code approach:
exports.getById = async (req) =>{
let id = `"` + req.body.accountId +`"`;
let accountId = await db.collection('account-details').find({id}).toArray();
return accountId
}
In request body, I am passing accountId as :
{
"accountId":"a1"
}
The ID is in the form of string. When I am trying to fetch whole records with the provided ID through my API, I am getting response as []. Can anyone please help me on this
You cannot send a body with an HTTP GET, therefore it will not be available in the req object, so req.body.accountId will be undefined and id will be an empty string.
You need to use POST (or PUT) to send body data.
But the more usual solution in your situation is to use GET with dynamic routing, where you add the id to the route e.g.: http://example.com/api/accounts/1234
If you use Express, in your router you need to add the route api/accounts/:id to your router. The id will be available in your code as req.params.id.
See Express docs. For other frameworks this will be something alike.
Hope this helps.
I am working on an app that responses are set like
req.data = data
I created a new endpoint, and if I console.log the data, I can see that mongoose is retriving the data. But postman is showing an empty array in the response
Also if I add
res.json(data)
Postman will show the json, but I don't want to change the app style
Probably I forgot to set something
Usually i use express to make API responses as the following :
app.get('/',(req,res)=>{
// some code goes here that will return DATA
res.status(200).json(DATA) // And This line will return a JSON file to postman
})
NOTE : use req.something to handle your incoming data, res.something to make a response to the client.
Hi I can connect to and store to mongodb using mlab but I can't get the data in the form to remain on refresh.
The form takes in user input from input-boxes.
Any help would be great.
Thanks
If being able to get the same form data for all the requests (no matter where they are made from)is what you want, then a possible workaround could be as follows:
1) Store the initial form data(probably empty) in the database, get the ObjectId and hard code it in your code, this way all the updates would be made to that specific MongoDB document only.
2) The form route (below one) should do nothing except for serving the file which has the form
app.get('/form1', function (req, res) {
res.sendFile(__dirname + '/public');
//record.find({"_id": ObjectId("MLAB ID")})......dont do this
});
3) There should be another route that sends form data
app.get('/getdata', function(req, res) {
record.find({"_id": ObjectId("MLAB ID")}, function(err, doc) {
res.send(doc)
})
});
4)The static file that you send to the client should have a javascript function such that it asks for the form data as soon as your window loads and then sets the value of input elements from that data recieved:
window.onload = function() {
//make a GET request to /getdata to get form data....store it in obj
//then set the input values
document.getElementById("yourchoice").value = obj.yourchoice;
//and set the value of other input fields ....in similar amnner
}
5) The POST request you make should update that specific document( findOneAndUpdate?? )
Disadvantage of this method:
For one operation we request a file from server and then another request to get form data, so two requests for one operation, since we cannot use both res.sendFile() and res.json() together...one way to get around this is to hide the form data as well in the HTML document using a template engine. More about this can easily be found. Anyways the above method does solve your purpose.
I hope I correctly understood the problem statement.
Happy coding!!
Edit:Although the above mentioned points are explainatory, I have written a sample snippet at : https://pastebin.com/AvgVyx7b
It works perfectly fine
I have a route in node - express and it is working properly - getting data from a database.
app.get('/getdata/:key', function(req, res){
console.log("Search key(s):", req.originalUrl.split("/")[2]);
keys = req.originalUrl.split("/")[2]
Keys = keys
arr = keys.split(",");
client.mget(arr, function (err, Values) {
res.send({ Keys, Values});
});
});
But I do not want to display all data (records) into the browser screen (DOM) - just want to get it as array and parse it later with some JavaScript in a browser.
How to achieve that?
If you are sending all data at once, so the client will not do another request. You must filter the data at the client's side.
As it is probably an array of objects, you could use .filter function.
Here you have some info about how to do the filtering: w3chools - JavaScript Array filter() Method
As #jfreind00 recommended - return it as JSON.
Perform a GET request with JS in your Front-end:
http.get('/getdata/${key}', (err, res) => {
// do something with your data here
}
Depending on your used frameworks this code could differ.
After posting in db.json a new record (transaction with several data), I would like to get the id of the new record before going on. How-to do it ? I am stuck
I have in my db.json a "table" positions with an id automatically generated
my request is
request({
url: url + '/api/positions,
method: 'POST',
form: transaction
}, ????);
I want in my callback retrieve position.id (as I have to use it in another part of code).
Thanks a lot
Olivier
Make sure your API is giving back the position id, Im assuming you're using express, so in /api/positions have the response be res.send({position...});
EDIT, So you're asking about routing? Here is an awesome guide: https://expressjs.com/en/guide/routing.html but Ill give you an example of what I mean.
app.post('/api/positions', function(req, res) {
//your logic goes here, so you are sending a 'transaction' object
// npm install and use body parser so you can retrieve attributes
// from the body of the post
res.send({position: x})
})
Maybe some thing like that.
...
var router = jsonServer.router('db.json');
...
// 'router.db.get' will fetch any first level attribute from your db.json
var positions = router.db.get('positions').value();
var lastPosition = positions[positions.length-1];