How to resolve setHeader issue in nodejs - node.js

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

Related

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received function wrappedCwd

This is my code
//Require modules
var http = require("http");
var url = require("url");
var path = require("path");
var fs = require("fs");
var mimeTypes = {
html: "text/html",
jpeg: "image/jpeg",
png: "image/png",
jpg: "image/jpg",
js: "text/javascript",
css: "text/css",
};
http
.createServer(function (req, res) {
var uri = url.parse(req.url).pathname;
var fileName = path.join(process.cwd, unescape(uri));
console.log("Loading " + uri);
var stats;
try {
stats = fs.lstatSync(fileName);
} catch (error) {
res.writeHead(404, { "Content-type": "text/plain" });
res.write("404 not Found");
res.end();
return;
}
if (stats.isFile()) {
var mimeType = mimeTypes[path.extname(fileName).split(".").reverse()[0]];
res.writeHead(200, { "Content-type": mimeType });
var fileStream = fs.createReadStream(fileName);
fileStream.pipe(res);
} else if (stats.isDirectory) {
res.writeHead(302, { location: "index.html" });
res.end();
} else {
res.writeHead(500, { "Content-Type": "text/plain" });
res.write("500 Internal Error");
res.end();
}
})
.listen(3000);
This is the error viewed in terminal:
> simpleserver#1.0.0 start C:\Users\User\Desktop\Codes\html workspace\node_temp\simpleserver
> node server.js
internal/validators.js:120
throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received function wrappedCwd
at validateString (internal/validators.js:120:11)
at Object.join (path.js:375:7)
at Server.<anonymous> (C:\Users\User\Desktop\Codes\html workspace\node_temp\simpleserver\server.js:20:25)
at Server.emit (events.js:315:20)
at parserOnIncoming (_http_server.js:790:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17) {
code: 'ERR_INVALID_ARG_TYPE'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! simpleserver#1.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the simpleserver#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\User\AppData\Roaming\npm-cache\_logs\2020-10-19T13_55_19_012Z-debug.log
I am new to nodeJS and I was learning from youtube tutorial. I have created index.html page as well. I am trying to run index.html page on : "http://127.0.0.1:3000/index.html".
I did exactly what they did. I rechecked for any error. Please Help me... Thanks in Advance
Change process.cwd to process.cwd(). You are using the syntax from an older version of node.js. Here’s the current API reference

Node JS error crash after handling custom error

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

eslint unnecessarily warning "promise/no-nesting" with Firestore transactions

I have Firestore data structured as follows:
I want to runTransaction() on the trend_score child. My function was working prior to adding the second .then(result =>, meaning now that I added another method to the cloud function, I am getting an error:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.handler = functions.firestore.document('/Polls/{pollId}/responses/{userId}').onCreate((data, context) => {
const answerSelected = data.data().answer;
const answerRef = admin.firestore().doc(`Polls/${context.params.pollId}/answers/${answerSelected}`);
const voteCountRef = admin.firestore().doc(`Polls/${context.params.pollId}`);
const trendScoreRef = admin.firestore.doc(`Polls/${context.params.pollId}/trend_score`);
return admin.firestore().runTransaction(t => {
return t.get(answerRef)
.then(doc => {
if (doc.data()) {
t.update(answerRef, { vote_count: doc.data().vote_count + 1 });
}
})
}).then(result => {
return admin.firestore().runTransaction(t => {
return t.get(voteCountRef)
.then(doc => {
if (doc.data()) {
t.update(voteCountRef, {vote_count:doc.data().vote_count+1});
}
});
});
//starting with this set, I believe this code has caused the issue
}).then(result => {
return admin.firestore().runTransaction(t => {
return t.get(trendScoreRef)
.then(doc => {
if (doc.data()) {
t.update(trendScoreRef, {trend_score:doc.data().trend_score+1});
}
});
});
});
Error
 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint 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! /Users/troychuinard/.npm/_logs/2018-11-10T02_02_56_229Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1
[1]: https://i.stack.imgur.com/etVwy.png
Once you resolve the syntax error, eslint is warning you that you have nested promises. This is normally not good, but since they are nested inside a transaction callback, there's actually not a problem here. You can disable that warning at the line where eslint finds it by adding this comment to the end of the lines that it warns you about:
return t.get(answerRef) // eslint-disable-line promise/no-nesting
.then(...)

Node.js throw new Error('Can\'t set headers after they are sent.');

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.!

Node js + imagemagick + Error: spawn ENOENT

Hi am trying to implement Imagemagick package using node.js
I added my following code.
var im = require('imagemagick');
router.post('/conversation/start', function(req, res) {
var args = ["/public/images/team/rajini.jpg", "-crop", "120x80+30+15", "output.png"];
im.convert(args, function(err) {
if (err) {
throw err;
}
res.end("Image crop complete");
});
});
But i getting the following error in terminal.
events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:988:11)
at Process.ChildProcess._handle.onexit (child_process.js:779:34)
npm ERR! weird error 8
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

Resources