router.get inside router.post, can't reach router.get - node.js

am trying to have a router.get inside router.post, I need to compare the information provided by the user to the one in the database and then post it if it does not exists. The problem is the router.get is never reached. No errors, and postman keeps "sending request" with no end. Is it possible to have a router.get inside router.post?, if yes how?, If no, how do I get info from router.get to pass to router.post? I need to run the api from ..../new, and do all the work from there. Thanks in advance
//register
router.post('/new', (req, res, next)=>{
console.log("jumped out");
var user_id, password0, password1;
user_id = req.body.user_id;
password0 = req.body.password0;
password1 = req.body.password1;
console.log(password1);
//retrieving usernames to check if it exists
router.get('/accounts', (req, res, next)=>{
console.log("in here");
detail.find(function(err, accounts){
//looping through usernames
for (var i=0; i<accounts.length; i++){
if (accounts[i].user_id === user_id){
res.json({msg: 'Username taken'});
}
else if(i == (accounts.length-1)){
if (password0 === password1){
let newAccount = new account({
user_id: this.user_id,
password: this.password0
});
newAccount.save((err, account)=>{
if(err){
res.json({msg: 'failed to create account'});
}
else{
res.json({msg: 'Account created successfully'});
}
});
}
else if (password0 !== password1){
res.json({msg: 'Password mismatch'});
}
}
}
//res.json(accounts);
});
});
});

I think the issue here is that you have a misunderstanding about what router.get is doing. It sounds like you want to accept a POST request from the user, then make a get request to check if the data already exists, and if not, then update your database.
If this is the case, the inner GET should actually use something like axios to make a request. You can make an axios request like this:
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
If you are actually trying to accept a second request from the user after the POST, then you should NOT do that. Users should only make one request for one action. You'll run into all kinds of issues down that path.

Turns out you can still retrieve data with only .POST, without having .GET. Removing the line having router.get, fixed the problem.
router.get('/accounts', (req, res, next)=>{

Related

Can't set headers after they are sent when using dbquery multiple times

I get this error #Can't set headers after they are sent# when using dbquery multiple times.
Hi, I'm almost new to node.js and I can't figure out why this error appears. If I try with one dbquery then everything is ok. But if I use multiple query then it crashes.
router.get(
'/auth/facebook/token',
(req, res, next) => {
passport.authenticate('facebook-token', (error, user, info) => {
if (user){
myDB.setUser(user.email,(err,pinfo) =>{
if (err) {
res.send(err);
}
else {
res.send(pinfo); <- Crash at this line!!!
}
});
}
next();
})(req,res, next);
}
);
function setUser (email, cb) {
pool.query("INSERT INTO users (email,pinfo) VALUES (?,0)", email, (err, result) => {
if(err){
cb(err);
return;
}
else{
pool.query("SELECT pinfo FROM users WHERE email = ?", email,(err,pinfo) =>{
cb(err,pinfo);
});
}
});
}
You are calling next middle layer function using next(). After sending the response to the user. Try without next or modify your logic to. Hope this will help you
once you are used res.send you cannot use it again
it seems you are sending a response at two positions please check the logic thoroughly
Some Where you sending response twice and hence this error. R.sarkar is right take out next() call and add it somewhere you will want to continue with your next dbquery or else respond from top function only once and never call next().

Response with JSON on request-promise .catch() function

I've found that all my request-promise .catch() methods are using the same logic in my application. So, I would like to write one maintainable function like so:
var handleError = function (error) {
if (error.statusCode == 401) {
res.json({
'message': 'You\'re no longer logged in. Please check your settings and try again.'
});
} else {
res.json({
'message': 'Something when wrong and it wasn\'t your fault. Please try again.'
});
}
};
router.get('/test', function(req, res, next) {
request({
uri: 'http://google.com/404'
}).then(function () {
console.log('It worked!');
}).catch(handleError);
});
Although this doesn't work because the handleError() function doesn't have access ExpressJS's response object. How can I return JSON to the page and still maintain everything from one function?
In that case, it's best to write a middleware to handle it.
Alternatively, you can bind res object but again you will have to bind it everywhere to use.
You can learn more about express middleware on its homepage
Also, see express-promise package

express post 500 error without router/subsite

My setup is as follows:
posting to /register will take the arguments and register a user via passport and mongoose. If this returns an UserExistsError the server sends this info to the client (via http error handling).
However the server also displays a 500 server error which should not occur.
This is because of the next() which as far as I understand routes the client to /register. /register itself does not exists as a page (only as the postadress as stated in the code)
So my question is: How to handle the response to not be an error or supress it? Can I use something else instead of next() to stop the redirect to /register? I just want the server to stop doing anything/going out of that function at that point.
Code:
app.post('/register', function(req, res, next) {
console.log('server registering user');
User.register(new User({username: req.body.username}), req.body.password, function(err) {
let tempstring = ""+err;
if(tempstring.indexOf("UserExistsError") !== -1){
return next(err); //get out of the function and into normal operation under '/'
}
});
});
This topic is bugging me and I might just missunderstand something trivial.
Even if /register is a post only route you still need to send a response. If you don't send a response of some kind, the request will hang and eventually timeout in the browser. I would suggest sending a json response like so.
app.post('/register', function(req, res, next) {
console.log('server registering user');
User.register(new User({username: req.body.username}), req.body.password, function(err) {
let tempstring = ""+err;
if(tempstring.indexOf("UserExistsError") !== -1){
return next(err); //get out of the function and into normal operation under '/'
}
res.json({message: 'message here'});
});
});
This will send a 200 OK reponse with some json in the body.
If you just want to pass the request down the line you need to call next without an err object like so.
app.post('/register', function(req, res, next) {
console.log('server registering user');
User.register(new User({username: req.body.username}), req.body.password, function(err) {
let tempstring = ""+err;
if(tempstring.indexOf("UserExistsError") !== -1){
return next(err); //get out of the function and into normal operation under '/'
}
//call next without an error
next();
});
});
I am not sure if this is what you are trying to achieve, but if there is no route that matches it will just go to an error 500.

Express.js Routing error: Can't set headers after they are sent

I'm not really sure why I'm getting this error. It's a simple API built on express.js to be able to add and remove posts. The error occurs when I trigger the delete router. I've read that the error typically happens when there are two callbacks, however, I don't seem to be able find any double callbacks.
_http_outgoing.js:344
throw new Error('Can\'t set headers after they are sent.');
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js:718:10)
at ServerResponse.send (/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js:163:12)
at ServerResponse.json (/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js:249:15)
at /Users/bounty/Projects/_learning/react-express/server/routes/posts.js:86:9
at nextTickCallbackWith0Args (node.js:452:9)
at process._tickCallback (node.js:381:13)
Here is my posts.js router:
module.exports = function(router) {
var Post = require('../models/post.js');
// middleware for the api requests
router.use(function(req, res, next) {
// do logging
console.log('something is happening.');
next(); // make sure we go to our next route and don't stop here
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// all routes here
// routes that end in /posts
router.route('/posts')
// create a Post (accessed at POST http://localhost:7777/api/posts)
.post(function(req, res) {
var post = new Post();
post.postTitle = req.body.postTitle; // set the post name (comes from request)
// save post and check for errors
post.save(function(err) {
if (err)
res.send();
res.json({ message: 'post created!' });
});
})
// get all Posts (accessed at GET http://localhost:7777/api/posts)
.get(function(req, res) {
Post.find(function(err, posts) {
if (err)
res.send();
res.json(posts);
});
});
// routes that end in /posts for specific id
router.route('/posts/:post_id')
// get the post with that id
.get(function(req, res) {
Post.findById(req.params.post_id, function(err, post) {
if (err)
res.send(err);
res.json(post);
});
})
// update the post with that id
.put(function(req, res) {
Post.findById(req.params.post_id, function(err, post) {
if (err)
res.send(err);
post.postTitle = req.body.postTitle;
// save the post
post.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'post updated!' });
});
});
})
// deletes the post with that id
.delete(function(req, res) {
Post.remove({
_id: req.params.post_id
}, function(err, post) {
if (err) {
res.send(err);
}
res.json({ message: 'post deleted!' });
});
});
}
You need to add the 'return' so that you don't reply twice.
// save post and check for errors
post.save(function(err) {
if (err) {
return res.send();
}
res.json({ message: 'post created!' });
});
That particular error message is pretty much always caused because of a timing error in the handling of an async response that causes you to attempt to send data on a response after the response has already been sent.
It usually happens when people treat an async response inside an express route as a synchronous response and they end up sending data twice.
One place I see you would get this is in any of your error paths:
When you do this:
// save post and check for errors
post.save(function(err) {
if (err)
res.send();
res.json({ message: 'post created!' });
});
If post.save() generates an error, you will do res.send() and then you will do res.json(...) after it. Your code needs to have a return or an else so when there's an error you don't execute both code paths.
So, this can happen in Express when attempting to send res.end twice which res.send and res.json both do. In your if(err) block you'll want to return res.send() as res.send runs asynchronously and res.json is getting called as well. I'm wondering if you're getting an error in your delete route? Hope this helps.
Best!
You are using res.send() or res.json() twice in the same request
this send the headers first, followed by body of the response and then headers again.
req.next is usually not a function, next is rather passed as a third argument of the middleware. Use that if you want to drop to the next middleware. (assuming you are using Express framework)
Just for the sake of completeness I will also mention that:
Sometime problem may be in a the middleware you may be using by calling
app.use.
After checking for obvious errors as mentioned in previous answers:
You should remove all the app.use statement then reintroduce them one by one, to find problematic module.
If you are using res.send() inside any loop, then you need to break it after the use of res.send(). So that it won't allow resetting of the res headers again and again.
for e.g :
for(){
if(){
res.send();
break;
}
else(){
res.send();
break;
}
}
In my case this is the problem and I solved it like this.
Hope it may help someone in future.
Thanks
For a quick fix you can just check res.finished before calling res.send():
if (!res.finished)
res.send()

expressjs - using middleware function

I would like to know how I can move the following code into a separate function (in the same file) and call upon it when either I call the POST or PUT routes to add or update documents.
I'm using https://www.npmjs.org/package/express-validator
The following is currently in my POST route but when I'm updating a record the title will still need to be validated.
app.post('/docs', auth, function (req, res) {
req.checkBody('title', 'Title is required').notEmpty();
var errors = req.validationErrors();
if(errors){
res.json(400, { errors: errors });
return;
}
//go ahead and save the document
});
I've tried making my own function but I'm not sure where to put the var errors = req.validationErrors(); or whether it's bad practice to return 400 errors from a separate function.
Any help/code much appreciated.
The body of the middleware function is almost identical to the code you are using right now, only with two notable differences:
The function ensures that the req.method is either POST or PUT.
The next() function is called when validation passes. This will trigger the next middleware function in the chain, or the route handler.
app.use('/docs', function(req, res, next) {
if (req.method == 'POST' || req.method == 'PUT') {
req.checkBody('title', 'Title is required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.json(400, { errors: errors });
return;
}
}
next();
});
app.post('/docs', auth, function (req, res) {
// go ahead and save the document
});

Resources