the problem is the following. I'm using node js with express and mongo db for my backend. I'm new with node js so I will try to explain the problem.
I'm creating a endpoint to validate a confirmation code for emails validation and it's working fine when I found the problem doing a return and showing a code 200, but I want to display another error when is not found. So after try to validate a invalid code the backend crash and show the following error.
CONTROLLER
function confirmation(req, res, next) {
userService.confirmate(req.body)
.then (res.status(200).json({status:"ok"}))
.catch(err => next(err));
}
SERVICE
async function confirmate(body) {
User.findOneAndUpdate({token: body.code}, {$set: {isVerified: true}}, {upsert: false}, function(err,doc) {
if (err) {
// SOME ERROR
console.log(' error');
throw err; }
if (!doc) {
// NOT FOUND HANDLER
console.log('not found);
throw new Error('example')
}
// FOUNDED!
console.log("Updated");
return;
});
}
ERROR HANDLER
module.exports = errorHandler;
function errorHandler(err, req, res, next) {
if (typeof (err) === 'string') {
// custom application error
return res.status(400).json({ message: err });
}
if (err.name === 'ValidationError') {
// mongoose validation error
return res.status(400).json({ message: err.message });
}
if (err.name === 'UnauthorizedError') {
// jwt authentication error
return res.status(401).json({ message: 'Invalid Token' });
}
// default to 500 server error
return res.status(500).json({ message: err.message });
}
ERROR
D:\DESARROLLO\menuon-project\be-server\node_modules\mongodb\lib\utils.js:132
throw err;
^
Error: example
at D:\DESARROLLO\menuon-project\be-server\users\user.service.js:88:23
at D:\DESARROLLO\menuon-project\be-server\node_modules\mongoose\lib\model.js:4690:16
at model.Query.Query._completeOne (D:\DESARROLLO\menuon-project\be-server\node_modules\mongoose\lib\query.js:1932:12)
at cb (D:\DESARROLLO\menuon-project\be-server\node_modules\mongoose\lib\query.js:3285:11)
at D:\DESARROLLO\menuon-project\be-server\node_modules\mongoose\lib\query.js:3376:14
at D:\DESARROLLO\menuon-project\be-server\node_modules\mongoose\lib\query.js:4093:12
at result (D:\DESARROLLO\menuon-project\be-server\node_modules\mongodb\lib\utils.js:414:17)
at session.endSession (D:\DESARROLLO\menuon-project\be-server\node_modules\mongodb\lib\utils.js:401:11)
at ClientSession.endSession (D:\DESARROLLO\menuon-project\be-server\node_modules\mongodb-core\lib\sessions.js:129:41)
at executeCallback (D:\DESARROLLO\menuon-project\be-server\node_modules\mongodb\lib\utils.js:397:17)
at handleCallback (D:\DESARROLLO\menuon-project\be-server\node_modules\mongodb\lib\utils.js:128:55)
at executeCommand (D:\DESARROLLO\menuon-project\be-server\node_modules\mongodb\lib\operations\collection_ops.js:558:12)
at handleCallback (D:\DESARROLLO\menuon-project\be-server\node_modules\mongodb\lib\utils.js:128:55)
at db.s.topology.command (D:\DESARROLLO\menuon-project\be-server\node_modules\mongodb\lib\operations\db_ops.js:516:5)
at D:\DESARROLLO\menuon-project\be-server\node_modules\mongodb-core\lib\connection\pool.js:532:18
at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
at D:\DESARROLLO\menuon-project\be-server\node_modules\mongoose\lib\model.js:4692:13
at model.Query.Query._completeOne (D:\DESARROLLO\menuon-project\be-server\node_modules\mongoose\lib\query.js:1932:12)
[... lines matching original stack trace ...]
at process._tickCallback (internal/process/next_tick.js:61:11)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-mongo-registration-login-api#1.0.0 start: `node ./server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-mongo-registration-login-api#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Franco\AppData\Roaming\npm-cache\_logs\2019-08-10T16_55_39_844Z-debug.log
Related
I have done file uploading process in my application using connect-multiparty.I can upload file and move to local folder.Everything is working perfect except below issue.I do not know why i am getting this error.How to resolve this issue?How to avoid this error.
app.js:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var fs = require('fs');
app.post('/api/upload', multipartMiddleware, (req, res) => {
res.json({ 'message': req.files });
var tmp_path = req.files.uploads[0].path;
var target_path = './uploads/' + req.files.uploads[0].name;
fs.rename(tmp_path, target_path, function(err) {
if (err) throw err;
console.log("Upload started")
fs.unlink(tmp_path, function() {
if (err) throw err;
res.send('File uploaded to: ' + target_path);
});
});
res.end();
});
upload.component.ts:
upload(){
let formData = new FormData();
for(var i = 0; i < this.uploadedFiles.length; i++) {
formData.append("uploads[]", this.uploadedFiles[i], this.uploadedFiles[i].name);
}
this.http.post(environment.apiBaseUrl+'/upload', formData)
.subscribe((response)=>{
console.log('response receved is ', response);
})
}
Error:
_http_outgoing.js:526
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:526:11)
at ServerResponse.header (C:\xampp\htdocs\testing\server\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (C:\xampp\htdocs\testing\server\node_modules\express\lib\response.js:170:12)
at C:\xampp\htdocs\testing\server\app.js:65:17
at FSReqCallback.oncomplete (fs.js:154:23) {
code: 'ERR_HTTP_HEADERS_SENT'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! project#1.0.0 dev: `node app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the project#1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\ADMIN\AppData\Roaming\npm-cache\_logs\2020-05-21T17_06_06_701Z-debug.log
I am trying to PUT mongoose data using postman but it shows "TypeError: bear.save is not a function" in server console and crash the node app.
In this problem I am running two apps on different ports and db with the same code, normal http app can make all requests(POST,PUT,DEL,GET) success but another https app can't make PUT request, it can only make POST and GET successfully .
I can't understand why the same code on http app not showing error if it was code problem. Please help me.
REST API reference from - Here
.get(function(req, res) {
Bear.find( {ID: req.params.bear_id} , function(err, bear) {
if (err)
res.send(err);
res.jsonp(bear);
});
})
.put(function(req, res) {
Bear.find( {ID: req.params.bear_id}, function(err, bear) {
if (err)
res.send(err);
bear.Name = req.body.Name;
//res.json(bear) can send data up to this line
// save the bear (crash after following line)
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear updated!' });
});
})
});
Error Log on console -
TypeError: bear.save is not a function
at Promise.<anonymous> (/var/www/vhosts/mydomain.com/nodeapp.js:130:18)
at Promise.<anonymous> (/var/www/vhosts/mydomain.com/node_modules/mpromise/lib/promise.js:162:8)
at emitOne (events.js:96:13)
at Promise.emit (events.js:188:7)
at Promise.emit (/var/www/vhosts/mydomain.com/node_modules/mpromise/lib/promise.js:79:38)
at Promise.fulfill (/var/www/vhosts/mydomain.com/node_modules/mpromise/lib/promise.js:92:20)
at /var/www/vhosts/mydomain.com/node_modules/mongoose/lib/query.js:1736:26
at model.Document.init (/var/www/vhosts/mydomain.com/node_modules/mongoose/lib/document.js:251:11)
at completeMany (/var/www/vhosts/mydomain.com/node_modules/mongoose/lib/query.js:1734:12)
at cb (/var/www/vhosts/mydomain.com/node_modules/mongoose/lib/query.js:1697:11)
You probably want to use findOne instead of find.
I'm trying to work with IBM Watson Conversation service with Node.js.
I use 'express' to post a message:
app.post( '/api/message', function(req, res) {
}
and to print the message got from the service:
conversation.message( payload, function(err, data) {
if ( err ) {
return res.status( err.code || 500 ).json( err );
}
return res.json( updateMessage( payload, data ) );
} );
I just ran the application on port 3000. While the page is not loaded and I got this error:
_http_server.js:192
throw new RangeError(`Invalid status code: ${statusCode}`);
^
RangeError: Invalid status code: 0
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:573:10)
at ServerResponse.send (C:\IBM\1.Mission\2016\conversation-simple-master(1)\
conversation-simple-master\node_modules\express\lib\response.js:204:10)
at ServerResponse.json (C:\IBM\1.Mission\2016\conversation-simple-master(1)\
conversation-simple-master\node_modules\express\lib\response.js:249:15)
at C:\IBM\1.Mission\2016\conversation-simple-master(1)\conversation-simple-m
aster\app.js:86:44
at Request._callback (C:\IBM\1.Mission\2016\conversation-simple-master(1)\co
nversation-simple-master\node_modules\watson-developer-cloud\lib\requestwrapper.
js:47:7)
at self.callback (C:\IBM\1.Mission\2016\conversation-simple-master(1)\conver
sation-simple-master\node_modules\watson-developer-cloud\node_modules\request\re
quest.js:200:22)
at emitOne (events.js:77:13)
at Request.emit (events.js:169:7)
I don't think the problem is from npm, back my package... While it seems a generic problem...Thanks for you help.
Request to IBM Watson Conversation service probably ended with error with code "0" and it isn't a valid HTTP status code. This should work:
conversation.message(payload, function(err, data) {
if (err) {
return res.status(500).json(err);
}
return res.json(updateMessage(payload, data));
});
This the error:
{}
_http_outgoing.js:335
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:335:11)
at ServerResponse.setWriteHeadHeaders (D:\xampp\htdocs\wisaa\node_express\node_modules\morgan\node_modules\on-headers\index.js:80:19)
at ServerResponse.writeHead (D:\xampp\htdocs\wisaa\node_express\node_modules\morgan\node_modules\on-headers\index.js:39:36)
at ServerResponse.writeHeader (_http_server.js:233:18)
at Object.queue.drain (D:\xampp\htdocs\wisaa\node_express\routes\index.js:52:13)
at D:\xampp\htdocs\wisaa\node_express\node_modules\async\lib\async.js:871:23
at D:\xampp\htdocs\wisaa\node_express\node_modules\async\lib\async.js:44:16
at D:\xampp\htdocs\wisaa\node_express\routes\index.js:43:21
at Socket.<anonymous> (D:\xampp\htdocs\wisaa\node_express\node_modules\email-verify\index.js:145:13)
at Socket.emit (events.js:129:20)
npm ERR! Windows_NT 6.2.9200 npm ERR! argv "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start" npm ERR! node v0.12.5 npm ERR! npm v2.11.2 npm ERR! code ELIFECYCLE npm ERR! node_express#0.0.0 start: `node ./bin/www` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the node_express#0.0.0 start script 'node ./bin/www'. npm ERR! This is most likely a problem with the node_express package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node ./bin/www npm ERR! You can get their info via: npm ERR! npm owner ls node_express npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request: npm ERR! D:\xampp\htdocs\wisaa\node_express\npm-debug.log`
This is my code:
var express = require('express');
var router = express.Router();
var _ = require('underscore');
var fs = require('fs'),
async = require('async'),
verifier = require('email-verify');
/* GET home page. */
router.post('/', function(req, res, next) {
var emails = req.body.emails;
emails = emails.split(',');
var queue = async.queue(function(task, callback) {
task(callback);
}, 100);
_.each(emails, function(e, i) {
queue.push(function(cb) {
var done = false;
verifier.verify(e, function(err, info) {
if (err) {
//console.log(err);
// fauile
emails.splice(emails.indexOf(e), 1);
var score = "Your email is nor valid neither exist";
} else {
if (info.success) {
// success
res.json({
'message': emails
});
} else {
emails.splice(emails.indexOf(e), 1);
}
}
if (!done) {
done = true;
cb(null, true);
console.log('something bad happened!');
}
});
});
});
queue.drain = function() {
console.log(arguments);
res.writeHeader(200, {
'content-Type': 'text/plain'
});
res.send(JSON.stringify(emails));
res.end();
}
});
module.exports = router;
It looks like you'll be calling res.json() one or more times per request. That's not allowed because it sends the response (and headers hence error). There should be only one response per request.
When you do _.each, you're making a loop. In this case, you're adding a bunch of functions to a queue. When each function in that queue is processed you're calling res.json(). res.json() sends a response which is something you can only do once, not multiple times.
You can do any kind of processing of the emails that you need in this queue if you need to but don't actually send it with res.json until the callback is called, so in drain.
As already pointed out by #Matt Harrison , i am trying to add little description to it only.
It looks like,
res.json({
'message':emails
});
is getting called first which is responsible for sending the json response to the client, hence completing the request-response cycle.
So, after this point any attempt on res object is immaterial as response has already been sent.
Since you are getting following exception
new Error('Can\'t set headers after they are sent.');
So, most probably, queue.drain() is called, which is setting the header. At this point you are getting the error.
try:
verifier.verify(e, function(err, info) {
if (err) {
//Return the error itself
return res.send(err);
//The rest of your code here
...
}else{...}
you need to add the 'return' so that you don't reply twice. In a nutshell, Your code needs to have a return or an else so when there's an error you don't execute both code paths. That's where the error is coming from in my opinion.
Hope this helps.!
var cradle = require('cradle');
var db = new(cradle.Connection)().database('starwars');
db.get('vader', function (err, doc) {
doc.name;
assert.equal(doc.force, 'dark');
});
db.save('skywalker', {
force: 'light',
name: 'Luke Skywalker'
}, function (err, res) {
if (err) {
// Handle error
} else {
// Handle success
}
});
installed cradle via npm
npm install cradle
The error output running node cradle.js
root#server:~# node cradle.js
/root/cradle.js:5
doc.name;
^
TypeError: Cannot read property 'name' of undefined
at Object.callback (/root/cradle.js:5:8)
at /root/node_modules/cradle/lib/cradle.js:276:26
at IncomingMessage.<anonymous> (/root/node_modules/cradle/lib/cradle.js:210:21)
at IncomingMessage.emit (events.js:81:20)
at HTTPParser.onMessageComplete (http.js:133:23)
at Socket.ondata (http.js:1213:22)
at Socket._onReadable (net.js:681:27)
at IOWatcher.onReadable [as callback] (net.js:177:10)
UPDATE: problem boils down to
db.get('vader', function (err, doc) {
doc.name;
assert.equal(doc.force, 'dark');
});
it's complaining about doc.name
Where can I view the database so I can see the new row added?
db.get('vader', function (err, doc) {
if (err) {
console.log(err);
} else {
doc.name;
assert.equal(doc.force, 'dark');
}
});
The example doesn't do error handling. I would assume the error is document vader doesn't exist or database starwars doesn't exist.
If you have couch installed and running then the database lives at http://localhost:5984/_utils/