Weird (intermittent) Can't set headers after they are sent error - angularjs

Have a very strange intermittent problem, and one that I just can not understand at all. Not certain it is code related, bug in express or just me missing something.
Have an app, all in MEAN, that like so many other apps around does a bunch of API calls. Some even in parallel.
It all worked perfect this morning, actually, read the "where it gets weird", but then all of a sudden it stops working and the server starts falling over with the below error:
GET /api/skillList 304 45.345 ms - -
_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.header (/Users/bengtbjorkberg/WebstormProjects/ResourceEdge/node_modules/express/lib/response.js:695:10)
at ServerResponse.json (/Users/bengtbjorkberg/WebstormProjects/ResourceEdge/node_modules/express/lib/response.js:232:10)
at /Users/bengtbjorkberg/WebstormProjects/ResourceEdge/routes/api.js:78:9
at /Users/bengtbjorkberg/WebstormProjects/ResourceEdge/node_modules/mongoose/node_modules/kareem/index.js:160:11
at Query._findOne (/Users/bengtbjorkberg/WebstormProjects/ResourceEdge/node_modules/mongoose/lib/query.js:1145:12)
at /Users/bengtbjorkberg/WebstormProjects/ResourceEdge/node_modules/mongoose/node_modules/kareem/index.js:156:8
at /Users/bengtbjorkberg/WebstormProjects/ResourceEdge/node_modules/mongoose/node_modules/kareem/index.js:18:7
at process._tickCallback (node.js:355:11)
Process finished with exit code 1
What I have checked.
Threw tons of log messages, looks like it falls over at different places, or I am missing one of the places
Spent a lot of time looking at the last call (/api/skilllist), to be working quite OK.
Where it gets REALLY weird
If I start the developer console in Chrome, the problem DOES NOT OCCURE, which is probably why it worked all day but then stopped working when I wanted to show it to someone...
While I was writing this, I realised that I could use safari, and it falls over with the java console on, and it is the same line server side. And its the database call below. But if I turn the console on in Chrome, it starts working... What am I missing
exports.canlist = function (req, res) {
// use mongoose to get all profiles in the database
console.log("Canlist called");
Profile.find( {}, {'_id':1, 'alias':1, 'img':1, 'summary':1, 'keys':1}, function(err, profiles) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
console.log("Error " + err)
res.send(err)
}
console.log("Sending back " + profiles.length + " profiles")
res.json(profiles); // return all todos in JSON format
});
};

So, after much faffing about, I figured it out. Not why it works when using java console it open on Chrome.
Basically the res.send(err) command is wrong.
First its missing return.
Secondly I THINK you are suppose to use the longer form like this:
return res.status(500).send(err);
return res.json(profile);
Think the problem was that it was confusing express, which probably do some pre processing, which may explain why it "seems" to blow up at all kind of times.
(Would have kept quiet about this, as it is a bit of a ridiculous mistake, but it saves someone a few hours staring at the screen I might get a christmas card this year. (or at least get to tell santa that I've been a good boy)

Related

axios.post update my mongodb but returns undefined using async await in react

i would like to mention that i used postmen and got results as expected so no problem with server side. and also it does update my db but doesnt send the results;
(so whene i debug it never reaches line 10 looks like it stoped execution , i tried to console. log (data) and nothing show up... )
thanks in advenced!!!

SAD PANDA: TypeError: failed to fetch

​ === SAD PANDA ===
TypeError: Failed to fetch
=== SAD PANDA ===
While executing a flow cadence transaction in react.js, I got the above error.
My intention is when I click the minttoken button, this transaction has to execute so as to mint the NFT.
const mintToken = async() => {
console.log(form.name)
const encoded = await fcl.send([
fcl.proposer(fcl.currentUser().authorization),
fcl.payer(fcl.authz),
fcl.authorizations([fcl.authz]),
fcl.limit(50),
fcl.args([
fcl.arg(form.name,t.String),
fcl.arg(form.velocity,t.String),
fcl.arg(form.angle,t.String),
fcl.arg(form.rating,t.String),
fcl.arg(form.uri,t.String)
]),
fcl.transaction`
import commitContract from 0xf8d6e0586b0a20c7
transaction {
let receiverRef: &{commitContract.NFTReceiver}
let minterRef: &commitContract.NFTMinter
prepare(acct: AuthAccount) {
self.receiverRef = acct.getCapability<&{commitContract.NFTReceiver}>(/public/NFTReceiver)
.borrow()
?? panic("Could not borrow receiver reference")
self.minterRef = acct.borrow<&commitContract.NFTMinter>(from: /storage/NFTMinter)
?? panic("could not borrow minter reference")
}
execute {
let metadata : {String : String} = {
"name": name,
"swing_velocity": velocity,
"swing_angle": angle,
"rating": rating,
"uri": uri
}
let newNFT <- self.minterRef.mintNFT()
self.receiverRef.deposit(token: <-newNFT, metadata: metadata)
log("NFT Minted and deposited to Account 2's Collection")
}
}
`
]);
await fcl.decode(encoded);
}
this error being so useless is my fault, but I can explain what is happening here because it also only happens in a really specific situation.
Sad Panda error is a catch all error that happens when there is a catastrophic failure when fcl tries to resolve the signatures and it fails in a completely unexpected way. At the time of writing this it usually shows up when people are writing their own authorization functions so that was the first thing i looked at in your code example. Since you are using fcl.authz and fcl.currentUser().authorization (both of those are the same by the way) your situation here isnt because of a custom authorization function, which leads me to believe this is either a configuration issue (fcl.authz is having a hard time doing its job correctly) or what fcl is getting back from the wallet doesn't line up with what it is expecting internally (most likely because of an out of date version of fcl).
I have also seen this come up when the version of the sdk that fcl uses doesnt line up with the version of the sdk that is there (because some people have added #onflow/sdk as well as #onflow/fcl) so would also maybe check to make sure you only have fcl in your package.json and not the sdk as well (everything you should need from the sdk should be exposed from fcl directly, meaning you shouldnt need the sdk as a direct dependency of your application)
I would first recommend making sure you are using the latest version of fcl (your code should still all work), then i would make sure you are only using fcl and not inadvertently using an older version of the sdk. If you are still getting the same error after that could you create an issue on the github so we can dedicate some resources to helping sort this out (and make it so you and others dont see this cryptic error in future versions of fcl)

PollingConsumer using smb protocol and pollEnrich()

Problem: The file is not consumed from the server
I am using
from("test")
.routeId("test")
.pollEnrich()
.simple("smb://myUrl?password=test&fileName=${in.headers.test}")
.aggregationStrategy((Exchange oldExchange, Exchange newExchange) -> {
//do things
return newExchange;
})
I have no error, I am sure that the url is ok, because when I am using the same url in the from(), the file gets consumed.
I don't understand what is happening here, I am using camel 2.24.0 and camel-extra:camel-jcifs:2.23.1. I have tried to use smb2 using the library from github.jborza.camel-smbj, still the same outcome.
I tried to debug, I can see in the GenericFileComponent class in the createEndpoint method, that the endpoint is correctly created, then I tried (in debug mode) to get the exchanges from my endpoint, I can get them successfully, further this will be a SmbEndpoint, when I try to get the exchanges from my smbEndpoint it returns exactly the needed file from the server, further a EventDrivenPollingConsumer is created for this endpoint, I had a look at it, is started (seems ok). When it hits the consumer.receive() from the PollEnricher it blocks, no file is consumed. I tried using a timeout, than returns null, so somehow cannot find the file, or the consumer is wrong, I honestly have no clue at this point.
I had a look here too: https://github.com/apache/camel/blob/b9a3117f19dd19abd2ea8b789c42c3e86fe4c488/core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumePollEnrichFileTest.java
and I have played with delays
&consumer.initialDelay=100&consumer.delay=100&consumer.bridgeErrorHandler=true
Then I tried to implement with processor like here:
https://github.com/apache/camel/blob/b9a3117f19dd19abd2ea8b789c42c3e86fe4c488/core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumePollEnrichFileUsingProcessorTest.java
The same result :(
At some point the file was consumed, suddenly, but this happened only once, I cannot understand this behavior.
Sounds that you have a readlock problem, can you find any files in .done with the same name as the file you try to consume?

Spontaneous Server Errors During AngularJS $http calls

I'm building an SPA in AngularJS served by a Laravel (5.1) backend. Of late I've been encountering an annoying error, a server 500 or code 0 error which is abit hard to explain how it comes but let me try to may be someone will understand the dental formula of my problem.
When i start my AngularJS controller, I make several server calls (via independent $http calls from services) to retrieve information i might later need in the controller. For example,
Functions.getGrades()
.then(function(response)
{
$scope.grades = response.data;
});
Subjects.offered()
.then(function(response)
{
$scope.subjects = response.data;
});
Later on i pass these variables (grades or subjects) to a service where they are used for processing. However, these functions are randomly returning code 500 server errors after they run, and sometimes returning status code 0 after running. This happens in a random way and it is hard for me to point out the circumstances leading to their popping up. This leaves me with frequent empty Laravel-ised error screens like the ones shown below.
Anyone reading my mind?
Ok, after a suggestion given in a comment above that I check my Laravel log files (located in storage/logs/laravel.log- Laravel 5.1), i found out that the main error most of these times was this one: 'PDOException' with message 'SQLSTATE[HY000] [1044] Access denied for user ''#'localhost' to database 'forge'' in ..., plus another one that paraphrased something like No valid encrypter found. These were the key opener.
On reading another SO thread here, it said in part:
I solved, sometimes laravel not read APP_KEY in .ENV. And returns a value "SomeRandomString" (default is defined in config / app.php), and have the error "key length is invalid", so the solution is to copy the value of APP_KEY, to the value 'key 'in config / app.php, that's all! I solved!
That was exactly the issue! When loading the DB params from the .env to config/database.php, Laravel was sometimes unable to read the environment variables and went for the fallback default fallback options (forge for DB name and username and SomeRandomString for the APP_KEY). So, to solve this i just did as advised: copied the APP_KEY in .env to the config/app.php and edited the default DB parameters to the actual DB name and username/password I'm using. Just that and i was free from pollution. Hope someone finds this helpful.

$window.open called in a promise breaks the second promise

I am pretty new to angularjs. Love it but sometimes get surprises that I just can't find an answer.
I have a function that lets the user build a list to a file by clicking a link. This can take up to a minute so the user can build different lists at the same time. The meaning is that once the file is build a popup appears to download it.
All of this works when only 1 file is build. After a half a minute the download popup shows up. But when 2 are build at the same time the second POST is cancelled (it arrives in the error callback) once the pop-up of the first appears.
If I remove $window.open both POST are finished succesfully and I get both fileId's in the console log.
Clearly the problem lies with $window.open. But why? What am I doing wrong or how can I solve this? Anyone an idea? I have been searching for hours already but can't seem to find anything on this case.
$scope.idPromise = $http.post(restPath, $scope.data)
.then(function(data){
console.log(data.data);
console.log(data.data.fileId);
$window.open(restPath + 'files/' + data.data.fileId, '_self');
},function(error){
console.log('promise error')
});
So when two lists are build without window.open in the code I get something like this in my console:
POST http://localhost:8080/xxx-rest/rest/lijsten/vastelijsten/gezinshoofdenMetLeden 200 OK 1m
POST http://localhost:8080/xxx-rest/rest/lijsten/vastelijsten/gezinshoofdenMetLeden 200 OK 1m 40s
report3545743463669473959.xlsx
report4733168386603499105.xlsx
when window.open is placed in the code:
POST
http://localhost:8080/xxx-rest/rest/lijsten/vastelijsten/gezinshoofdenMetLeden
200 OK 1m
POST
http://localhost:8080/xxx-rest/rest/lijsten/vastelijsten/gezinshoofdenMetLeden
x 56,39s
report1588183186872251177.xlsx
promise error
As you can see the last POST is stopped as soon as the first POST gets a response, so for the second POST no response is gotten.
Update
It seems the problem lies with the grunt server and the liveReload Protocol. My college had always told me to ignore this error but it is now clear that because the page loses connection that the promise fails.
Does anyone have experience with grunt and liveReload? Can I fix this? Will it work on a production server?
The console error I get:
De verbinding met ws://localhost:35729/livereload werd onderbroken
tijdens het laden van de pagina. this.socket = new
this.WebSocket(this._uri);
(translated: the connection with... was interrupted)

Resources