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.
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 learning by building. I am building a blog management system using Reactjs, Nodejs, Mongodb.
I would like to store some frontend values in the database so that anyone I give admin permission can post, edit and delete such values. These values are website name, sub-name, sidebar bio description, header image and bio image.
This is the code to create the value:
//create new frontend paramters into database
router.post("/", async (req, res) =>{
const newFrontendValues = new Frontend(req.body);//we called the frontend model we created and we used req.body
try{
const savedFrontendValues = await newFrontendValues.save()//we tried to save the frontend values created
res.status(200).json(savedFrontendValues)
}catch(err){
res.status(500).json(err)
}
});
I wrote the code in node to get the values like this after creating them:
//get frontend parameters
router.get("/:id", async (req, res) =>{
try{
const frontend = await Frontend.findById(req.params.id)
res.status(200).json(frontend)
}catch(err){
res.status(500).json(err)
}
})
my server api code
app.use("/api/frontend", frontend)
In react, I wanted to call the _id of the values but I am lost. I really don't know how to go about that.
It is working fine as desired in postman because I can directly implement the value _id.
See attached image
But in React, I wanted that to be dynamic.
Here is my React code:
useEffect(() => {
const fetchFrontendValue = async () =>{
const res = await axios.get("/frontend")
console.log(res.data)
}
fetchFrontendValue()
}, [])
How do I add the _id to this
axios.get("/frontend")
You'd want to look at get request parameters. Usually as a convention, people pass them in the URL. So it would be something like http://localhost:5000/api/frontend?id=617944dc7e00022337a483be78 and on the API side, you'd use req.body.id to pass that to the database. There are other ways to do it too, but this is the most common because some old browser drop the parameters attached to a GET request. Here's a link:https://www.w3schools.com/tags/ref_httpmethods.asp
You should consider going for a complete solution. On a basic level, you should be following these steps
Implement a backend route /getall that fetch out all items in DB in this manner
await Frontend.find({})
Render the fetched list on frontend side in a way that each item would be a React UI item and as part of each item, you have the buttons for deleting and updating the item data
{backendData?.map((item, index)=><SingleItem key={item?._id} data={item} />)}
As each SingleItem has update and delete buttona and also the mongodb ID as part of data, so on clicking update and delete button, you will get the id from the data and call relevant DB Url on backend side
I'm sending a post request to a cloud function which contains the following body:
{message: "this is the message"}
If I try to print the entire body of the request, it shows it, but if I try to get the message field, I get undefined in the console.
Here's my function:
exports.myCloudFunction = functions.https.onRequest((req: any, res: any) => {
console.log(req.body)\\prints the body of the request fine
console.log(req.body.message)\\prints "undefined"
cors(req, res, () => {
const pl = req.body.message;
console.log(pl);\\prints "undefined"
});
return res.send("all done")
});
You don't need a body parser for Cloud Functions as described in the other answer here. Cloud Functions will automatically parse JSON and put the parsed JSON object in the body attribute. If you want this to happen automatically, you should set the content type of the request to "application/json" as described in the linked documentation. Then you can use req.body as you'd expect.
I personally haven't worked with firebase before, but from your code and the fact that req.body prints the body, it seems that you probably need to parse the request-body as json in order to be able to access the message property:
const body = JSON.parse(req.body);
console.log(body.message);
It could also be the case that you need to setup a bodyparser for json content. In a normal express-app you can do this using (note that you don't need the manual parsing from above anymore using bodyparser):
const bodyParser = require('body-parser');
app.use(bodyParser.json();
EDIT:
see Doug's answer for the correct way to do this, i.e. to fix your request and set the content-type to application/json in order for Cloud Functions to automatically parse and populate req.body with the request body.
You need to just convert the request body into a JSON object in cloud function.
const body = JSON.parse(req.body);
// message
console.log(body.message)
i am beginner so i apologize if my question isn't relevant or easy to fix, but i couldn,t fix my issue yet, for 4 days.
I am working on an api, which will receive data from angular form, then store it with sequelize on a mariadb table.
When i submit my form, which would through the url, post it in the table through the api, i can see that the req.body is defined, and it reachs the api, but yet i have and error in my angular http post which is thrown(error 500).
With postman, i see that my url isn t reachable, i can't figure out so if my error comes from the post angular, or the backend with my model, even if error 500 is for back end.
I tried to redefine my sequelize model, parse and stringify the object i send, try others url...but nothing works.
So here is my function called when the form is submitted,the function formatrequestschedulest return the object i want to post.
onSubmitScheduled(){
let OndemandScheduledRequest = this.formatRequestScheduled(this.selectedHotel, this.selectedCheckInDate, this.selectedCheckOutDate, this.selectedNumber, this.selectedCurrency, this.selectedReportName, this.selectedUser, this.selectedEmail, this.selectedFormat);
console.log(OndemandScheduledRequest);
this.saveScheduledRequest(OndemandScheduledRequest);
return this.openDialog();
}
saveScheduledRequest(onDemandScheduledRequest: OnDemandScheduledRequest){
this.http.post('/api/ScheduledReport', JSON.stringify(onDemandScheduledRequest), {headers: {'Content-Type': 'application/json'}})
.subscribe(res=>{ console.log(res
)
console.log('ok')},
(err) =>
console.log('an error'))
/*console.log(err))*/
}
And here is my api:
var request= require('../controller/ondemandscheduledrequests');
var router = express.Router();
router.get('/getreport',request.create);
router.post('/ScheduledReport',request.create);
I can provide also the error i get, but i don't know if i can join a picture to the question.
I just want to have my form data store to my table, but i get an error 500 instead.
this is the error i get
Use pipe like below and try once
this.http.post('/ScheduledReport', JSON.stringify(onDemandScheduledRequest).pipe().subscribe(val => {
console.log(val, "service");
, {headers: {'Content-Type': 'application/json'}})}
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).