Node.JS run routes synchronously - node.js

In this example, I have two routes - the first is a Get route and the second is a Post route. I want the information gathered in the get route to be included in the post route. I tried using .then and some basic boolean if logic but I cannot get these routes to run synchronously.
leadFormObj = {};
$.get("/getID/"+leadFormObj.parentEmail, function(event){
console.log("getting an ID");
console.log(event[0].id);
leadFormObj.parentID = event[0].id;
});
console.log(leadFormObj);
$.post("/addChild", leadFormObj, function(data) {
console.log(leadFormObj);
console.log("sent");
});
In the example above, I have a standard object (i've shown it blank in this example). The first get route will run and pass in a new key value pair to the object. I then want to pass this updated object to the post route but I'm not sure how to do this.
Would I use nested routes to do this?
Thanks!

Why don't you put the post request inside the callback of the get request
$.get("/getID/"+leadFormObj.parentEmail, function(data){
$.post("/addChild", {parentID: data[0].id}, function(data) {
console.log("sent");
});
});

Related

how can we use delete http request in NodeJS

when i try to delete data by this code its not working
router.delete('/delete-screen/:id',(req,res)=>{
let proId=req.params.id
console.log(proId)
theaterHelpers.deleteOwner(proId).then((response)=>{
res.redirect('/theater/screens')
})
})
but using this code it working
router.get('/delete-screen/:id',(req,res)=>{
let proId=req.params.id
console.log(proId)
theaterHelpers.deleteOwner(proId).then((response)=>{
res.redirect('/theater/screens')
})
})
what i done is replace delete to get, My question is how can make a http delete request in my code
my delete function code is
deleteScreen:(screenId)=>{
return new Promise((resolve,reject)=>{
db.get().collection(collection.SCREEN_COLLECTION).removeOne({_id:ObjectID(screenId)}).then((response)=>{
console.log(response)
resolve(response)
})
})
}
If you're using a server-rendered application, then you can only issue GET and POST requests. The only way to trigger a delete route handler is to trick your application into thinking the incoming request actually has DELETE semantics. You can do this by modifying the request.method property before the request is actually handed to the router.
There are a number of ways to achieve this, and the method-override package has got you covered.
For instance, the following setup would update request.property for incoming GET requests to the value provided with the _method query parameter.
var methodOverride = require('method-override')
app.use(methodOverride("_method", { methods: ["GET"] }))
Then, accordingly add a _method query parameter with the DELETE value to the url you want to use to trigger you delete route handler.
yourUrl?_method=DELETE
https://www.npmjs.com/package/method-override

How to set Routes for APIs

I am building an API to manage meetups with nodeJS. I have build an endpoint with the route "/meetups/:id/" to fetch a specific meetup record by its id. And then I want to fetch all the upcoming meetup records and I tried to use "/meetups/upcoming/" but when I query it, I get the not found error (404). It seems like the second route is not recognised.
Here is the code defining the two routes
the request from postman
Any help on how can I handle that?
Thanks.
Route is '/api/v1/meetups/upcoming/all'. Move res.status outside the map function.
EDIT: you'll have to change the route which has to be different from api/v1/meetups/:id. Reason is when route '/api/v1/meetups/upcoming' is requested express sees it as the same route as before and takes 'upcoming' as the parameter.
app.get("/api/v1/meetups/upcoming/all", function(req, res) {
var today = new Date();
var upcomings = db.meetups.map(function(meetup) {
if(meetup.happeningOn > today) {
return meetup;
}
});
res.status(200).send({
status: 200,
data: upcomings
});
});
You need to move the res.status piece outside of the const upcomings definition.

POST not working for Mocha/Chai tests on Express REST API

I'm having a problem with Mocha tests on my Express app. I have a REST API set up that I know works in the browser, but it's getting a bit large and therefore manual testing has become tedious.
Anyway, all my GET tests work just fine, but when I add tests for my POST requests, they fail:
Uncaught AssertionError: expected { Object (domain, _events, ...) } to have status code 200 but got 400
at testPostSingle (test-app.js:297:21)
at test-app.js:195:21
at Test.Request.callback (/home/jacobd/healthboard/node_modules/chai-http/node_modules/superagent/lib/node/index.js:603:3)
at Stream.<anonymous> (/home/jacobd/healthboard/node_modules/chai-http/node_modules/superagent/lib/node/index.js:767:18)
at Unzip.<anonymous> (/home/jacobd/healthboard/node_modules/chai-http/node_modules/superagent/lib/node/utils.js:108:12)
at _stream_readable.js:944:16
I'm using Mocha, with the Chai should library and chai-http for requests.
My relevant code:
models.forEach(function(model, i) {
var url = '/api/v1/' + model;
var list = lists[i];
/****************************** API POST TESTS ******************************/
describe(util.format('API: /%s POST', model), function() {
var minArgsObj = {
title: 'Test ' + model + ' Title'
};
// Initialize list at start
before(function(done) {
instances._init(function(err) {
if (!err) done();
});
});
// Nuke list before each test
beforeEach(function(done) {
list.clear();
done();
});
// Make sure POST single object works
it('should create and add model on ' + url + ' with minimal arguments', function(done) {
var req = {};
req.options = _.clone(minArgsObj);
chai.request('server')
.post(url)
.send(req)
.end(function(err, res) {
testPostSingle(res, minArgsObj);
list.list.length.should.equal(1);
res.body.should.eql(list.list[0]);
done();
});
});
});
});
function testPostSingle(res, ref) {
res.should.have.status(200);
...
}
When I put a log message in the POST route declaration, it doesn't show up, so that tells me that my request is getting stopped before even hitting my server. Maybe the route isn't getting mounted properly in Mocha? It works when I make the request outside of Mocha, but I can't figure out why it won't work in a test environment.
Thanks in advance for your help, and let me know if you need any more info!
The relevant code is in testPostSingle. Your call is returning 400 bad request. Are you sure the route is correct or is set up to handle POST as well as GET? Are you sure parameters are correct? Make testPostSingle print out the body of the HTTP response so you know the details. You can also add some debug code in the route for that request on your server.
I'm terrible and issue is very simple:
Instead of chai.request('server')
It needs to be chai.request(server)
Thanks to Jason Livesay for pointing me at the right line!

ExpressJS is stacking up

Im trying to make an API that works through the power of the framework nodejs and the node module/package express
I made an API that once you call localhost:3000/?username=nameHere
It makes some http requests using the request module, waits for the callback and then sends the result out as html to the person requesting localhost:3000/?username=nameHere
However if I refresh it quickly, the ending result would be a stack of 2 results instead of one
Example: localhost:3000/?username=nameHere would return 1 array
if i quickly call/refresh it 2 times, the route acts the same for everyone and the ending result would stack up 2 arrays
How do I overcome this? I'm seriously new to routing.
Here's my code, app is simply express() and i Did define some variables at the top, GetAllItems basically is a function that does a bunch of requests made by the the request module, wraps up all the data and sends it back as a callback
app.use('/', function(req, res,next) {
console.log("request");
if (req.query.username!==undefined) {
GetID(req.query.username,function(ID){
if(ID!==undefined || ID!=="undefined"){
console.log("Cool");
GetAllItems(ID,function(cb){
res.send(JSON.stringify(cb));
next();
});
}else{
console.log("Not found");
res.send("Not Found");
}
})
}else{
res.send("No username");
}});

How to get req and res object of Expreejs in .ejs file

I am trying to use Express js with .ejs views.
I want to redirect my page to some another page on any event let say "onCancelEvent"
As per Express js documentation,I can do this by using res.redirect("/home");
But I am not able to get res object in my ejs file.
Can anyone Please tell me how to access req and res object in .ejs file
Please help.
Thanks
Short Answer
If you want to access the "req/res" in the EJS templates, you can either pass the req/res object to the res.render() in your controller function (the middleware specific for this request):
res.render(viewName, { req : req, res : res /* other models */};
Or set the res.locals in some middleware serving all the requests (including this one):
res.locals.req = req;
res.locals.res = res;
Then you will be able to access the "req/res" in EJS:
<% res.redirect("http://www.stackoverflow.com"); %>
Further Discussion
However, do you really want to use res in the view template to redirect?
If the event initiates some request to the server side, it should go through the controller before the view. So you must be able to detect the condition and send redirect within the controller.
If the event only occurs at client side (browser side) without sending request to server, the redirect can be done by the client side javascript:
window.location = "http://www.stackoverflow.com";
In my opinion: You don't.
It is better to create the logic that determines the need to redirect inside some middleware that happens long before you call res.render()
It is my argument that your EJS file should contain as little logic as possible. Loops and conditionals are ok as long as they are limited. But all other logic should be placed in middleware.
function myFn( req, res, next) {
// Redirect if something has happened
if (something) {
res.redirect('someurl');
}
// Otherwise move on to the next middleware
next();
}
Or:
function myFn( req, res, next) {
var options = {
// Fill this in with your needed options
};
// Redirect if something has happened
if (something) {
res.redirect('someurl');
} else {
// Otherwise render the page
res.render('myPage', options);
}
}

Resources