I am trying to call an api using axios in react.I am using express and node js .when api is called using axios.get() .it returns error after some time.when i run node in port 4000(localhost:4000/data) its not loading.
//api
router.route('/issue').get((req, result) => {
Issue.find((err, issue) => {
if (err)
console.log(err);
else
result.json(issue);
});
});
//api call in react file
axios.get('http://localhost:4000/issue').then(res=>{
console.log('success');
}).catch(err=>{
console.log('error');
});
You need to handle the error in your api. If you just console.log, your frontend is still waiting for a response
And if your back don't sent any response, your browser cancel the request with a timeout, that is the error you got
//api
router.route('/issue').get((req, result) => {
Issue.find((err, issue) => {
if (err)
result.status(404).json({
success: false,
msg: "There has been a problem in your request"
});
else
result.json(issue);
});
});
Related
I am sending a delete request using axios from my React frontend to node js express backend with mongo DB. Although the data does get deleted from my database but I still get an error 404 Not Found.
Here is React code
axios
.delete(`http://localhost:8000/notes/${id}`)
.then(res => {
console.log("The response is "+res.data)
})
.catch(err => {
console.log("There was an error "+ JSON.stringify(err.response))
});
Here is node js express code app.js
app.delete("/notes/:notesId", cors(), function(req, res) {
const query={_id:req.params.notesId};
console.log("The notes id is "+ query);
Note.findOneAndDelete(query, function(err) {
if(!err) {
console.log("The item got successfully deleted");
res.redirect("/");
} else {
console.log(err)
}
})
})
Please note that the entry gets deleted from my database but i get this error in my browser console :
xhr.js:178 DELETE http://localhost:8000/ 404 (Not Found)
App.jsx:26 There was an error {"data":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot DELETE /</pre>\n</body>\n</html>\n","status":404,"statusText":"Not Found","headers":{"content-length":"142","content-type":"text/html; charset=utf-8"},"config":{"url":"http://localhost:8000/notes/5ee130b65dc5f521acf60f38","method":"delete","headers":{"Accept":"application/json, text/plain, */*"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}
I am trying to hit the complete url till notes id but it is only considering till root
Try modifying the res to send a 200 OK status if the object gets deleted. You could also send a message for your frontend to display in this manner
if(!err) {
res.status(200).json({ message: 'The item got successfully deleted', error: false });
} else {
res.status(500).json({message : 'Oops and error occurred', error : true});
Regardless a simple res.status(200).end(); should suffice as well for your situation.
I'm trying to test an endpoint that should receive a multipart/form-data. I'm sending a collection of images, which i want to process and save on the server or CDN. I'm using Jest, Express and Formidable.
Endpoint
router.post("/videos", async (req, res) => {
new formidable.IncomingForm().parse(req, (err, fields, files) => {
console.log('PARSE FORM');
if (err) {
console.error('Error', err);
throw err
}
console.log('Fields', fields);
console.log('Files', files);
for (const file of Object.entries(files)) {
console.log('FILE', file)
}
});
res.status(200).send('Created Video');
});
Test
describe("Video Endpoints", () => {
it('should create a new timelapse video', done => {
request
.post('/api/videos')
.field('file', 'some random value')
.attach('image', `${__dirname}/__mocks__/image.png`)
.then(res => {
console.log('THEN');
done();
})
});
});
When running the test it doesn't reach the formidable parse method.
If change my my attach method to this...
.attach('image', fs.readFileSync(`${__dirname}/__mocks__/xdebugcurlaccessingwpapi.png`))
It will reach the parse method but it sees the it as field and not a file.
If i make the same request but from my react app using fetch, it works perfectly fine.
What am i doing wrong? Been on this for a few days now lol.
Any help would be great.
Thanks.
I'm not entirely sure why but if you add
.set({connection: 'keep-alive'})
Then it works.
Final solution
request
.post('/api/videos')
.set({connection: 'keep-alive'})
.field('name', 'Richard')
.attach('image', mockImage)
.then(res => {
console.log('THEN');
done();
});
});
Would be good if someone has an understanding to why this is the case.
I think it might close the stream to image but can't be sure.
I am currently writing a route which allows me to recieve information from a stored procudre I have in a database. I have written a request in AngularJS and a route in NodeJS but I am just recieving a pending request in the chrome Network developer window. I can see that the console.log in the NodeJs app has the data I require so it has retrieved it but there is nothing coming back in any of the console logs in the the AngularJS app.
Here is the code for the both the angularJS app and the Node App:
AnglaurJS:
checkForReplenishmentEmptyTrolley = async () => {
LIBRIS.extensions.openLoadingModal();
console.log('in checkForReplenishmentEmptyTrolley');
try {
const varPromise = await $http.get(`${LIBRIS.config.stockService}stockMovement/checkForUnattachedTrolley`)
.then((response) => {
console.log(response);
// Request completed successfully
}, (error) => {
// Request error
console.log(error);
});
console.log(varPromise.data);
// 1. check that there are no ghost replenish - lines 1-15
console.log('in try/catch');
console.log('promise', varPromise);
} catch (error) {
console.log(error);
}
},
NodeJS code:
app.get(`${ROUTE}/attachTrolley`, async function(req, res){
const newRequest = await DB.newRequest();
console.log('we have made it to the route');
try {
console.log('we have made it to the Try/Catch route');
newRequest.input();
const record = await newRequest.execute('dbo.usp_STK_CheckForUnattachedTrolley');
res.json(record)
console.log(record, 'record');
} catch (err){
handleError(res, err);
console.log(err);
}
});
The problem is that you are doing a .then on a awaited promises and not returning anything from that. You have two choice here
Either return response from then so when you try to access the value here console.log(varPromise.data); it works.
Or remove the .then alltogather as it is not required because you are awaiting it any ways.
Basically just do this
checkForReplenishmentEmptyTrolley = async () => {
LIBRIS.extensions.openLoadingModal();
console.log("in checkForReplenishmentEmptyTrolley");
try {
const varPromise = await $http.get(`${LIBRIS.config.stockService}stockMovement/checkForUnattachedTrolley`);
console.log(varPromise.data);
// 1. check that there are no ghost replenish - lines 1-15
console.log("in try/catch");
console.log("promise", varPromise);
} catch (error) {
console.log(error);
}
};
Hope this fixes your issue.
Solved it! I had no return statement in my route!
I'm using Ember.js alongside an Express webserver. The default JSONApi adapter calls update records with a PATCH request to the server setting the Request Payload in the request to the server.
I'm having a hard time getting that data out of the request on my express server
Here is an example request Ember is sending to the server
The relevant code for the express server looks like this
app.route('/tags/:id')
...
.patch(tag.updateTag);
// UpdateTag
function updateTag(req,res) {
Tag.findById({_id: req.params.id}, (err,tag) => {
if(err) res.send(err);
Object.assign(tag, req.body).save((err,tag) => {
if(err) res.send(err);
res.json(TagSerializer.serialize(tag));
});
});
}
I was able to get this working. In express I'm also using the jsonapi-serializer npm module to do serialization and deserialization
Turns out I need to do my deserialization and in it's callback use the data to update with rolls eyes
function updateTag(req,res) {
TagDeserializer.deserialize(req.body,(err,deserializedTag)=>{
if(err){
res.send(err);
} else {
Tag.findById({_id: req.params.id}, (err,returnedTag) => {
if(err) res.send(err);
Object.assign(returnedTag, deserializedTag).save((err,updatedTag) => {
if(err) res.send(err);
res.json(TagSerializer.serialize(updatedTag));
});
});
}
})
}
I am building an Angular 4 and Node application. Once any user registers on the front-end, I am storing their data in the database, and then would like to send them a successful registration email using the nodemailer package.
Here's the Node js code:
router.post('/', function(req, res, next) {
SOME_DATABASE_FUNC() {
if(FAILED_CASE) {
return res.status(500).json({
title: 'An error occurred',
status: 500,
error: error
});
var mailOptions {...}
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
return res.status(500).json({
title: 'An error occurred',
status: 500,
error: error
});
}
console.log('Message', info.messageId, info.response);
return res.status(200).json({
message: 'Emailed successfully',
details: info
});
});
}
}
});
This code works perfectly, but it takes few seconds to send the email, and the user has to wait to show the success response which doesn't seem to fit good. Instead I would like to send it in the background may be as an asynchronous function or like a cron job.
But I am not sure how to transform the code to send it as a job instead of sending and waiting after the database transaction. Please help me out with the issue.
send response outside block of transporter.sendMail. So it will not wait for process of email send to be completed.
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
return res.status(500).json({
title: 'An error occurred',
status: 500,
error: error
});
}
console.log('Message', info.messageId, info.response);
});
return res.status(200).json({
message: 'Emailed successfully',
details: info
});
use Process.nextTick() for sending email
We knew that nodejs request and response is stream and you can do stuff after sending response stream in this way response time will decrease and other stuff will continue asynchronously after sending response to client.
You can send response successfully to client and then you can call send mail function.