Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Http Headers related error with code pulled. #2362

Closed
madkid66 opened this issue Jul 22, 2016 · 69 comments
Closed

Http Headers related error with code pulled. #2362

madkid66 opened this issue Jul 22, 2016 · 69 comments
Labels
type:question Support or code-level question

Comments

@madkid66
Copy link

madkid66 commented Jul 22, 2016

We pulled parse-server code from master yesterday and while using that code, we notice the following stack trace in log for all the cloud calls being made. Anyone else seeing this? Also, any suggestions, tips for resolving this are appreciated. Thank you.

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
    at /var/app/current/node_modules/express/lib/application.js:153:9
    at /var/app/current/node_modules/express/lib/router/index.js:137:5
    at /var/app/current/node_modules/express/lib/router/index.js:250:10
    at next (/var/app/current/node_modules/express/lib/router/index.js:160:14)
    at next (/var/app/current/node_modules/express/lib/router/index.js:176:38)
    at Immediate.<anonymous> (/var/app/current/node_modules/express/lib/application.js:190:9)
    at Immediate.<anonymous> (/var/app/current/node_modules/parse-server/node_modules/express/lib/router/index.js:618:15)
    at Immediate.immediate._onImmediate (timers.js:435:18)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
@sprabs
Copy link

sprabs commented Jul 22, 2016

I'm noticing this, too. I had done a pull on master branch on 7/12. That had been working fine. When I pulled yesterday and deployed the newer parse server code, I started seeing this error. I suspect it must have been a commit that was introduced between 7/12 and 7/21.

@flovilmart Have you noticed this error, too?

@flovilmart
Copy link
Contributor

I haven't noticed it, not sure what would generate it.

@flovilmart
Copy link
Contributor

It doesn't seem to happen when using parse-server from the CLI, how did you configure/run it?
Can you provide more info about the code?

We recently added next handlers (#2338) this is maybe because your setup has a middleware that write the headers after they are written from parse-server

@madkid66
Copy link
Author

Thank you for the reply Florent.

We are running it on AWS Elastic Beanstalk on a t2.medium and seeing this error in the nodejs logs. The configuration of our environment has not changed over the last 3 weeks and we are running it with verbose set to true. The only thing we changed was we pulled the lasted parse-server code from master.

The error seems to happen any time a cloud code method is invoked. We use promises in our methods. It definitely seems to have been caused by the changes you pointed me to in PromiseRouter.js. Once I removed those changes in my local branch and redeployed, the errors went away. What is the purpose of those changes? Is that something that can be reverted? Or Is there something that our cloud-code needs to do to avoid seeing this error? Please share your thoughts on this.

@tillifywebb
Copy link

tillifywebb commented Jul 23, 2016

We are running on node chef, Our code is also now breaking. The issue appears that if we make any database queries from server code, cloud function or from express we get the fore mentioned error.

If we call queries from JS client - all works find. If we do anything server side we get the error. We have tried removing our app.js require so that our express set-up is removed, this did not fix the issue.

Can anybody help with this?

at Layer.handle as handle_request
at jsonParser (/bundle/node_modules/parse-server/node_modules/body-parser/lib/types/json.js:94:7)
at next (/bundle/node_modules/express/lib/router/index.js:271:10)
at Function.process_params (/bundle/node_modules/express/lib/router/index.js:330:12)
at /bundle/node_modules/express/lib/router/index.js:280:7
at trim_prefix (/bundle/node_modules/express/lib/router/index.js:312:13)
at Layer.handle as handle_request
at allowCrossDomain (/bundle/index.js:439:9)
at ServerResponse.header (/bundle/node_modules/express/lib/response.js:719:10)
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
Error: Can't set headers after they are sent.

@nitrag
Copy link

nitrag commented Jul 24, 2016

Seeing same error as well. AWS ElastBeanstalk, t2.micro, 64bit Amazon Linux 2016.03 v2.1.3, node version 4.4.6 (perhaps that's the issue?).

Errors are seen after running a cloud function, but my app still receives a valid response...

Parse.Cloud.define("getParks", function(request, response){

    if(!request.user){
        response.error();
        return;
    }

    var Parks = Parse.Object.extend("Park");
    var query = new Parse.Query(Parks);
    query.equalTo("Approved", true);

    query.find({useMasterKey: true}).then(function(results) {
        var parks = [];
        ..........
        return parks;
    }).then(function(parks) {
            response.success(parks);
        }, function(error) {
            response.error("Error: " + error.code + " " + error.message);
    });
});

@flovilmart
Copy link
Contributor

The fix seem pretty trivial as it looks like it originates from one of our middleware that's run after the cloud functions. As you have the error, can any of you work on a fix?

@tillifywebb
Copy link

We have rolled back the last update which has fixed the error. Not sure how we fix it, seems any cloud function throws an error, but response is sent.

@flovilmart
Copy link
Contributor

@madkid66 can you try #2381 's branch and let me know if it fixes?

@madkid66
Copy link
Author

@flovilmart thank you for the reply. Will try that and update.

@sprabs
Copy link

sprabs commented Jul 25, 2016

@flovilmart Thanks for the suggestion. I tried that branch you pointed us to but am still getting this error:

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at /var/app/current/node_modules/express/lib/application.js:153:9
at /var/app/current/node_modules/express/lib/router/index.js:137:5
at /var/app/current/node_modules/express/lib/router/index.js:250:10
at next (/var/app/current/node_modules/express/lib/router/index.js:160:14)
at next (/var/app/current/node_modules/express/lib/router/index.js:176:38)
at Immediate. (/var/app/current/node_modules/express/lib/application.js:190:9)
at Immediate. (/var/app/current/node_modules/parse-server/node_modules/express/lib/router/index.js:618:15)
at Immediate.immediate._onImmediate (timers.js:435:18)
at processImmediate as _immediateCallback

@tillifywebb @madkid66 Did it work for you both or are you still seeing the issue, too?

@madkid66
Copy link
Author

@sprabs We have tried that suggestion but still seeing the issue. Thank you

@flovilmart anything else we can try? Thank you

@jeffjen
Copy link

jeffjen commented Jul 26, 2016

This is related to middleware firing header indiscriminately even though a previous handler had already sent header.

@woodardj
Copy link

Why was #2338 merged? This seems like a pretty drastic change in behavior for those of us working on getting our self-hosted infrastructure set up.

It appears that now our /parse/classes/:className endpoint is continuing through (not surprising with the addition of a next() into our express app's auth code that's been working fine until 2.2.16 (or 2.2.17)

What's the recommendation here?

@blacha
Copy link
Contributor

blacha commented Jul 26, 2016

@woodardj it was a bug to not have it, You should always call next() in your express apps. It prevented actions after data was returned to the client. (Eg logging and analytics)

If you are having issues with this, there is more than likely something not quite right in the order of the app.use inside your express application.

The order is very important to app.use

app.use(function(req, res, next) {
    console.log('beforeParse');
    next();
});

app.use('/parse', ParseInstance);

app.use(function(req, res, next) {
    console.log('afterParse');
    next();
});

@madkid66
Copy link
Author

@flovilmart @blacha @woodardj @jeffjen @tillifywebb @sprabs
I am trying to understand the flow towards finding a fix for the issue. Since the 'next handlers' were introduced only recently, am assuming it is possible the param 'next' may or may not be passed depending on the code (depending on latest code or not) that is invoking these methods such as handleParseHeaders. I don't see any check (null/undefined for next) in middleware.js before invoking next(). Is it possible that this may the reason for failures we are seeing. Would it help to add if checks before invoking next() everywhere it is being invoked. Please share your thoughts and suggestions.

Thank you

@blacha
Copy link
Contributor

blacha commented Jul 27, 2016

@madkid66 Previously parse server was not running next() which broke the flow of express.

express sets up a list of handlers for each URL it handles, it will run that handler then wait for the handler to call next()

given a simple setup like the one in my previous comment the handlers for /parse would look something like: [ beforeParse, Parse, afterParse]

Before this change, Parse would not call next() so afterParse would never run.

The two places I would look into where this problem could occur is in Cloud Functions calling response.success or response.error multiple times, and in the Express app setup.

Something like this would cause issues (you need to return after response.error)

if (error) {
    response.error(error);
}
response.success()

The other area would be inside the express app. Take a look for any app.use that are called after the app.use('/parse', ParseServer)

I haven't had this change break any of my apps (All deployed to ElasticBeanstalk), which would make me think that their might be some inconsistent code in your cloud-functions/express setup.

If anyone has a simple example that breaks, I would love to get my hands on it.

@madkid66
Copy link
Author

@blacha Thank you for the detailed explanation. Will look at our code and get back with any questions.

@sprabs
Copy link

sprabs commented Jul 27, 2016

I'm glad we are having an open discussion about this. This is frustrating for my team as we are developing and I would like to get to the bottom of this. Apologies in advance for my long response, but I want to make sure we are on the same page here.

@blacha I'm not sure I understand your explanation about our Cloud Code being the issue, so let me provide details about my situation (that looks like at least four independent people are also complaining about):

  • We are running our parse server on AWS Elastic Beanstalk (t2 medium) with VERBOSE set to 1 in our dev environment. (Looks like you are also running this on EB with also the latest version of the parse-server code, so can we assume the part in the express app is the same for both of us?)
  • The Cloud Code that is deployed to our EB setup is identical to the Cloud Code that is running on parse.com. We have been running this same code (without ANY changes) for over a month (and it's also out in production on parse.com). We have had ZERO issues with it. Some more details about what I've tested/observed:
  1. Despite the errors on EB, the methods are performing exactly as expected. The clients are receiving the right data back and all the operations are being performed without any issues.
  2. I see the error for virtually ANY Cloud Code method we call through our EB endpoint.
  3. The logs are clean on parse.com.
  4. I feel Success/Error handling for Cloud Code is pretty fundamental and obvious to detect if there's a problem there. I am pretty confident that we are handling this correctly. As a sanity test, I intentionally just created a bad Cloud Code method that does this the wrong way and deployed it to parse.com. It gives me a real error that we don't get with our real code.

Based on this analysis (unless I am missing something), I don't think our Cloud Code is the culprit. Also, I think we all already know this, and it's been verified by several others, but when the commit in question is reverted, everything is just fine. We don't see the errors.

Please let me know if there is anything else we should check...

@tillifywebb @madkid66 @woodardj Please feel free to add, if there's anything I missed based on your own deployments. I think we all are in agreement that this needs to be fixed one way or another. Whether it's reverting this change or coming up with a solution on top of this merge...

@flovilmart Obviously, we can't be having these errors in production. It's affecting several of us on the GitHub issue (and probably more who haven't noticed it, yet). Please let us know how you suggest we proceed with this.

@steven-supersolid
Copy link
Contributor

@sprabs Would you be able to take your simplest failing Cloud Code function and remove functionality until it does as little as possible but still reproduces the bug?

AFAIK The backend for Cloud Code on parse.com does not use Express so we will not see this kind of error there. If we know the cause of the issue we can hopefully figure out a way for parse-server to be consistent with parse.com while at the same time being valid Express middleware.

@sprabs
Copy link

sprabs commented Jul 27, 2016

@steven-supersolid @blacha @flovilmart

It's happening for even a pretty simple Cloud Code method (from our main.js) without any promise chains. I'll just reproduce my code so you have the same info...

Here's a Cloud Code snippet:

Parse.Cloud.define("forceUpdateCheck", function(request, response) {

  var appVersion = request.params.appVersion;
  var deviceType = request.params.deviceType;
  var forceUpdateBool = "false"; //initialize to false to be safe

  var constantsQuery = new Parse.Query("Constants");
  constantsQuery.equalTo("name", "lastSupportedVersionNumber");
  constantsQuery.first({
    success: function(constantValue) {

      if (constantValue && constantValue != undefined) {
        var lastSupportedVersionNumber = (constantValue.get("valuesByDevice"))[deviceType]["versionNumber"];
        var updateMessage = (constantValue.get("valuesByDevice"))[deviceType]["message"]

        // massaging the version number to make it ordinal
        var adjustedLastSupportedVersionNumber = Number(lastSupportedVersionNumber.replace(/\./g, ''));
        var adjustedAppVersionNumber = Number(appVersion.replace(/\./g, ''));

        if (adjustedAppVersionNumber < adjustedLastSupportedVersionNumber) {
          forceUpdateBool = "true";
        }
      }

      // return force update metadata to the client
      if (forceUpdateBool == "true") {
        response.success({"forceUpdateBool": forceUpdateBool, "updateMessage": updateMessage});
      } else {
        response.success({"forceUpdateBool": forceUpdateBool});
      }

    },
    error: function(error) {
      response.error("forceUpdateCheck method failed with error: " + error.message);
    }
  });
});

Here's the error:

Result: {"forceUpdateBool":"false"} functionName=forceUpdateCheck, appVersion=1.5.7, deviceType=ios, result=undefined
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
    at /var/app/current/node_modules/express/lib/application.js:153:9
    at /var/app/current/node_modules/express/lib/router/index.js:137:5
    at /var/app/current/node_modules/express/lib/router/index.js:250:10
    at next (/var/app/current/node_modules/express/lib/router/index.js:160:14)
    at next (/var/app/current/node_modules/express/lib/router/index.js:176:38)
    at Immediate.<anonymous> (/var/app/current/node_modules/express/lib/application.js:190:9)
    at Immediate.<anonymous> (/var/app/current/node_modules/parse-server/node_modules/express/lib/router/index.js:618:15)
    at Immediate.immediate._onImmediate (timers.js:435:18)
    at processImmediate [as _immediateCallback] (timers.js:383:17)

For completion, I was also able to confirm that even with VERBOSE not enabled on my AWS Elastic Beanstalk app, I still see the error (above).

@blacha
Copy link
Contributor

blacha commented Jul 27, 2016

@sprabs I updated your comment to have formatting (So it is easier for me to read)

Ill try and reproduce your issue from my local instance today.

@oli107
Copy link

oli107 commented Jul 27, 2016

I am having exactly the same issue. Creating dummy CloudCode, it seems to return the error whenever there is a promise involved. Returning any item without a promise doesn't seem to throw the error. This includes any Parse Queries. I have stripped back my express app to only include mounting the Parse API and the result is the same. Any cloud code containing a promise crashes the app.

@blacha
Copy link
Contributor

blacha commented Jul 28, 2016

Does #2417 fix this problem?

@madkid66
Copy link
Author

@blacha Since I had same issue, I tried using the fix you suggested above. But, I am still seeing the errors. Thank you for your suggestion.

Error: Can't set headers after they are sent.

at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)

at /var/app/current/node_modules/express/lib/application.js:153:9

at /var/app/current/node_modules/express/lib/router/index.js:137:5

at /var/app/current/node_modules/express/lib/router/index.js:250:10

at next (/var/app/current/node_modules/express/lib/router/index.js:160:14)

at next (/var/app/current/node_modules/express/lib/router/index.js:176:38)

at Immediate.<anonymous> (/var/app/current/node_modules/express/lib/application.js:190:9)

at Immediate.<anonymous> (/var/app/current/node_modules/parse-server/node_modules/express/lib/router/index.js:618:15)

at Immediate.immediate._onImmediate (timers.js:435:18)

at processImmediate [as _immediateCallback] (timers.js:383:17)

Error: Can't set headers after they are sent.

at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)

at /var/app/current/node_modules/express/lib/application.js:153:9

at /var/app/current/node_modules/express/lib/router/index.js:137:5

at /var/app/current/node_modules/express/lib/router/index.js:250:10

at next (/var/app/current/node_modules/express/lib/router/index.js:160:14)

at next (/var/app/current/node_modules/express/lib/router/index.js:176:38)

at Immediate.<anonymous> (/var/app/current/node_modules/express/lib/application.js:190:9)

at Immediate.<anonymous> (/var/app/current/node_modules/parse-server/node_modules/express/lib/router/index.js:618:15)

at Immediate.immediate._onImmediate (timers.js:435:18)

at processImmediate [as _immediateCallback] (timers.js:383:17)

@bourquep
Copy link

I believe this is the same problem as #2389

@madkid66
Copy link
Author

@flovilmart can you please comment on what I should try or can anything be added in the parse-server code to fix this so that all affected don't have to individually come up with a solution. Thank you

@madkid66
Copy link
Author

madkid66 commented Aug 1, 2016

@flovilmart could you please spare few minutes to provide your valuable suggestion/comments with a fix for this issue. Just that several are running into the same problem. Thank you.

@BrennanH1
Copy link

BrennanH1 commented Aug 2, 2016

I am getting this issue as well, with trying to send a Push Notification through Cloud Code:
Error:

Error: Can't set headers after they are sent.
2016-08-02T17:41:48.829772+00:00 app[web.1]: at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
2016-08-02T17:41:48.829774+00:00 app[web.1]: at /app/node_modules/express/lib/router/index.js:137:5
2016-08-02T17:41:48.829774+00:00 app[web.1]: at /app/node_modules/express/lib/application.js:153:9
2016-08-02T17:41:48.829780+00:00 app[web.1]: at tryOnImmediate (timers.js:534:15)
2016-08-02T17:41:48.829776+00:00 app[web.1]: at next (/app/node_modules/express/lib/router/index.js:176:38)
2016-08-02T17:41:48.829775+00:00 app[web.1]: at /app/node_modules/express/lib/router/index.js:250:10
2016-08-02T17:41:48.829778+00:00 app[web.1]: at Immediate. (/app/node_modules/parse-server/node_modules/express/lib/router/index.js:618:15)
2016-08-02T17:41:48.829779+00:00 app[web.1]: at Immediate.immediate._onImmediate (timers.js:572:18)

I cant use any type of code in Cloud Code without getting it to throw this error.

@rgipd
Copy link

rgipd commented Aug 18, 2016

Hello, @flovilmart. I just forked "parse-server-example" and made few modifications (added two routes)
You can test locally the error with:

curl -X GET http://localhost:1337/register (to register and get a session token)

and then later:

curl -X GET http://localhost:1337/test2?sessionToken=r:xxxxx

The error is going to be the same as listed:

error: Error generating response. ParseError { code: 101, message: 'Object not found.' } code=101, message=Object not found.
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
....at next ....

My best regards.

@flovilmart
Copy link
Contributor

@rgipd can you provide what's in the ....at next .... as it contains very important information about the full call stack

@rgipd
Copy link

rgipd commented Aug 19, 2016

Ok, @flovilmart, it's below.
By the way, with [email protected] this error doesn't occurs.

My current path is /tmp/parse-server-example:
The log below

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
    at ServerResponse.header (/private/tmp/parse-server-example/node_modules/express/lib/response.js:695:10)
    at ServerResponse.send (/private/tmp/parse-server-example/node_modules/express/lib/response.js:146:12)
    at ServerResponse.json (/private/tmp/parse-server-example/node_modules/express/lib/response.js:235:15)
    at handleParseErrors (/private/tmp/parse-server-example/node_modules/parse-server/lib/middlewares.js:248:9)
    at Layer.handle_error (/private/tmp/parse-server-example/node_modules/parse-server/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/private/tmp/parse-server-example/node_modules/parse-server/node_modules/express/lib/router/index.js:310:13)
    at /private/tmp/parse-server-example/node_modules/parse-server/node_modules/express/lib/router/index.js:280:7
    at Function.process_params (/private/tmp/parse-server-example/node_modules/parse-server/node_modules/express/lib/router/index.js:330:12)
    **at next** (/private/tmp/parse-server-example/node_modules/parse-server/node_modules/express/lib/router/index.js:271:10)

How reproduce with my parse-server-example repository:

npm install
npm start

then:

curl -X GET http://localhost:1337/register

will output: {"result":"ok","sessionToken":"r:ffd0e2a886a7e843baaf3119d4bd6f6c"}
then:

curl -X GET http://localhost:1337/test2?sessionToken=r:ffd0e2a886a7e843baaf3119d4bd6f6c

will cause the error in parse-server (2.2.17, not on 2.2.0)

Regards.

@flovilmart
Copy link
Contributor

Did you register your routes before of after parse-server?

@rgipd
Copy link

rgipd commented Aug 19, 2016

It's after, just like parse-example-server guideline.

Check my index.js in my repository, but here is it:

// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);

// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
  res.status(200).send('I dream of being a website.  Please star the parse-server repo on GitHub!');
});

// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/test.html'));
});

app.get('/register', function(req, res) {

 Parse.User.signUp('testuser', 'testpass', {}).then(function (user) {
  console.log('testuser registered with success!');
  res.json({result: 'ok', sessionToken: user.getSessionToken()});
 }); 

});

app.get('/test2', function(req, res) {

 console.log('session token used: ');
 console.log(req.query);

  Parse.Cloud.httpRequest({
   method: 'GET',
   url: 'http://localhost:1337/parse/users/me',
   headers: {
    'X-Parse-Application-Id': 'myAppId',
    'X-Parse-Session-Token': req.query.sessionToken
   }
  }).then(function(userData) {
   res.json({result: 'ok'});
  });

});

var port = process.env.PORT || 1337;

PS: I updated the last answer with steps to reproduce.

@rgipd
Copy link

rgipd commented Aug 19, 2016

@flovilmart I just test with the routers before the parse-server and the result is the same:

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
    at ServerResponse.header (/private/tmp/parse-server-example/node_modules/express/lib/response.js:695:10)
    at ServerResponse.send (/private/tmp/parse-server-example/node_modules/express/lib/response.js:146:12)
    at ServerResponse.json (/private/tmp/parse-server-example/node_modules/express/lib/response.js:235:15)
    at handleParseErrors (/private/tmp/parse-server-example/node_modules/parse-server/lib/middlewares.js:248:9)
    at Layer.handle_error (/private/tmp/parse-server-example/node_modules/parse-server/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/private/tmp/parse-server-example/node_modules/parse-server/node_modules/express/lib/router/index.js:310:13)
    at /private/tmp/parse-server-example/node_modules/parse-server/node_modules/express/lib/router/index.js:280:7
    at Function.process_params (/private/tmp/parse-server-example/node_modules/parse-server/node_modules/express/lib/router/index.js:330:12)
    at next (/private/tmp/parse-server-example/node_modules/parse-server/node_modules/express/lib/router/index.js:271:10)

@flovilmart
Copy link
Contributor

I'm not sure what the problem is also note that the fix introduced here: #2475 has not been released yet

@steven-supersolid
Copy link
Contributor

I've been doing some investigation as can reproduce locally with parse-server master. The issue can be reproduced with the cli.

I added debug in node_modules/express/lib/response.js

res.header = function header(field, val) {
...
console.log('set header', field, val);

I ran the following with a valid access token:

curl -X GET -H "x-parse-application-id: appId" -H "x-parse-session-token: r:619a965488ef5e3dfa64bddda98b28fa" http://localhost:1337/parse/users/me

And got a valid response:

{"objectId":"xB7sPANhSu","username":"5Za5H2MR4WvEFTvX4zkhwSjfm","authData":{"anonymous":{"id":"1"}},"deviceId":"1","createdAt":"2016-08-20T11:07:07.987Z","updatedAt":"2016-08-20T11:07:07.987Z","ACL":{"*":{"read":true},"xB7sPANhSu":{"read":true,"write":true}},"__type":"Object","className":"_User","sessionToken":"r:619a965488ef5e3dfa64bddda98b28fa"}

The error is still displayed on the console log:

boinged@DESKTOP-6Q9DTR1:/mnt/d/development/parse-server$ npm start -- --appId appId --masterKey masterKey --databaseURI mongodb://localhost:27017/dev

> [email protected] start /mnt/d/development/parse-server
> node ./bin/parse-server "--appId" "appId" "--masterKey" "masterKey" "--databaseURI" "mongodb://localhost:27017/dev"

appId: appId
masterKey: ***REDACTED***
port: 1337
databaseURI: mongodb://localhost:27017/dev
mountPath: /parse
maxUploadSize: 20mb
verbose: 1
serverURL: http://localhost:1337/parse

parse-server running on http://localhost:1337/parse
set header Access-Control-Allow-Origin *
set header Access-Control-Allow-Methods GET,PUT,POST,DELETE,OPTIONS
set header Access-Control-Allow-Headers X-Parse-Master-Key, X-Parse-REST-API-Key, X-Parse-Javascript-Key, X-Parse-Application-Id, X-Parse-Client-Version, X-Parse-Session-Token, X-Requested-With, X-Parse-Revocable-Session, Content-Type
set header Access-Control-Allow-Origin *
set header Access-Control-Allow-Methods GET,PUT,POST,DELETE,OPTIONS
set header Access-Control-Allow-Headers X-Parse-Master-Key, X-Parse-REST-API-Key, X-Parse-Javascript-Key, X-Parse-Application-Id, X-Parse-Client-Version, X-Parse-Session-Token, X-Requested-With, X-Parse-Revocable-Session, Content-Type
verbose: REQUEST for [GET] /parse/users/me: {} method=GET, url=/parse/users/me, user-agent=curl/7.35.0, host=localhost:1337, accept=*/*, x-parse-application-id=appId, x-parse-session-token=r:619a965488ef5e3dfa64bddda98b28fa,
verbose: RESPONSE from [GET] /parse/users/me: {
  "response": {
    "objectId": "xB7sPANhSu",
    "username": "5Za5H2MR4WvEFTvX4zkhwSjfm",
    "authData": {
      "anonymous": {
        "id": "1"
      }
    },
    "deviceId": "1",
    "createdAt": "2016-08-20T11:07:07.987Z",
    "updatedAt": "2016-08-20T11:07:07.987Z",
    "ACL": {
      "*": {
        "read": true
      },
      "xB7sPANhSu": {
        "read": true,
        "write": true
      }
    },
    "__type": "Object",
    "className": "_User",
    "sessionToken": "r:619a965488ef5e3dfa64bddda98b28fa"
  }
} objectId=xB7sPANhSu, username=5Za5H2MR4WvEFTvX4zkhwSjfm, id=1, deviceId=1, createdAt=2016-08-20T11:07:07.987Z, updatedAt=2016-08-20T11:07:07.987Z, read=true, read=true, write=true, __type=Object, className=_User, sessionToken=r:619a965488ef5e3dfa64bddda98b28fa
set header Content-Type application/json
set header Content-Type application/json; charset=utf-8
set header Content-Length 349
set header ETag W/"15d-poQV49+JNu6wkXxU5NKY5A"
set header Access-Control-Allow-Origin *
error: Uncaught internal server error. [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 (/mnt/d/development/parse-server/node_modules/express/lib/response.js:720:10)
    at allowCrossDomain (/mnt/d/development/parse-server/lib/middlewares.js:229:7)
    at Layer.handle [as handle_request] (/mnt/d/development/parse-server/node_modules/express/lib/router/layer.js:95:5)
    at next (/mnt/d/development/parse-server/node_modules/express/lib/router/route.js:131:13)
    at Route.dispatch (/mnt/d/development/parse-server/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/mnt/d/development/parse-server/node_modules/express/lib/router/layer.js:95:5)
    at /mnt/d/development/parse-server/node_modules/express/lib/router/index.js:277:22
    at param (/mnt/d/development/parse-server/node_modules/express/lib/router/index.js:349:14)
    at param (/mnt/d/development/parse-server/node_modules/express/lib/router/index.js:365:14)
set header Content-Type application/json; charset=utf-8
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
    at ServerResponse.header (/mnt/d/development/parse-server/node_modules/express/lib/response.js:720:10)
    at ServerResponse.send (/mnt/d/development/parse-server/node_modules/express/lib/response.js:164:12)
    at ServerResponse.json (/mnt/d/development/parse-server/node_modules/express/lib/response.js:250:15)
    at handleParseErrors (/mnt/d/development/parse-server/lib/middlewares.js:275:9)
    at Layer.handle_error (/mnt/d/development/parse-server/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/mnt/d/development/parse-server/node_modules/express/lib/router/index.js:310:13)
    at /mnt/d/development/parse-server/node_modules/express/lib/router/index.js:280:7
    at Function.process_params (/mnt/d/development/parse-server/node_modules/express/lib/router/index.js:330:12)
    at next (/mnt/d/development/parse-server/node_modules/express/lib/router/index.js:271:10)

The final valid header is

set header ETag W/"15d-poQV49+JNu6wkXxU5NKY5A"

After this, PromiseRouter.makeExpressHandler is returning next() at line 181.

The 1st invalid header is

set header Access-Control-Allow-Origin *

Which seems to come from ParseServer.constructor at line 296:

    appRouter.use(middlewares.allowCrossDomain);

What is strange is that doing a user get gives no such error:

curl -X GET -H "x-parse-application-id: appId" -H "x-parse-session-token: r:619a965488ef5e3dfa64bddda98b28fa" http://localhost:1337/parse/users/xB7sPANhSu

In this case the server log looks like:

set header Access-Control-Allow-Origin *
set header Access-Control-Allow-Methods GET,PUT,POST,DELETE,OPTIONS
set header Access-Control-Allow-Headers X-Parse-Master-Key, X-Parse-REST-API-Key, X-Parse-Javascript-Key, X-Parse-Application-Id, X-Parse-Client-Version, X-Parse-Session-Token, X-Requested-With, X-Parse-Revocable-Session, Content-Type
set header Access-Control-Allow-Origin *
set header Access-Control-Allow-Methods GET,PUT,POST,DELETE,OPTIONS
set header Access-Control-Allow-Headers X-Parse-Master-Key, X-Parse-REST-API-Key, X-Parse-Javascript-Key, X-Parse-Application-Id, X-Parse-Client-Version, X-Parse-Session-Token, X-Requested-With, X-Parse-Revocable-Session, Content-Type
verbose: REQUEST for [GET] /parse/users/xB7sPANhSu: {} method=GET, url=/parse/users/xB7sPANhSu, user-agent=curl/7.35.0, host=localhost:1337, accept=*/*, x-parse-application-id=appId, x-parse-session-token=r:619a965488ef5e3dfa64bddda98b28fa,
verbose: RESPONSE from [GET] /parse/users/xB7sPANhSu: {
  "response": {
    "objectId": "xB7sPANhSu",
    "username": "5Za5H2MR4WvEFTvX4zkhwSjfm",
    "authData": {
      "anonymous": {
        "id": "1"
      }
    },
    "deviceId": "1",
    "createdAt": "2016-08-20T11:07:07.987Z",
    "updatedAt": "2016-08-20T11:07:07.987Z",
    "ACL": {
      "*": {
        "read": true
      },
      "xB7sPANhSu": {
        "read": true,
        "write": true
      }
    },
    "sessionToken": "r:619a965488ef5e3dfa64bddda98b28fa"
  }
} objectId=xB7sPANhSu, username=5Za5H2MR4WvEFTvX4zkhwSjfm, id=1, deviceId=1, createdAt=2016-08-20T11:07:07.987Z, updatedAt=2016-08-20T11:07:07.987Z, read=true, read=true, write=true, sessionToken=r:619a965488ef5e3dfa64bddda98b28fa
set header Content-Type application/json
set header Content-Type application/json; charset=utf-8
set header Content-Length 311
set header ETag W/"137-Gsk/6czKTBVcZLP3Xlyzlw"

The code in handleMe does not seem responsible as replacing this still reproduces the error.

@flovilmart
Copy link
Contributor

Nice investigation! That will probably help track down the issue. Odd that some end points don't reproduce the issue

@flovilmart flovilmart reopened this Aug 20, 2016
@steven-supersolid
Copy link
Contributor

Probing a little more, there seems to be some interference from the other route mounted on /users/ in UsersRouter. Disabling /users/:objectId removes the error. Not sure if this is related.

  mountRoutes() {
    this.route('GET', '/users', req => { return this.handleFind(req); });
    this.route('POST', '/users', req => { return this.handleCreate(req); });
    this.route('GET', '/users/me', req => { return this.handleMe(req); });
//    this.route('GET', '/users/:objectId', req => { return this.handleGet(req); });
    this.route('PUT', '/users/:objectId', req => { return this.handleUpdate(req); });
    this.route('DELETE', '/users/:objectId', req => { return this.handleDelete(req); });
    this.route('GET', '/login', req => { return this.handleLogIn(req); });
    this.route('POST', '/logout', req => { return this.handleLogOut(req); });
    this.route('POST', '/requestPasswordReset', req => { return this.handleResetRequest(req); })
  }

I thought the problem may have been because /users/me matches the first route, then matches the 2nd with a user id of 'me'. I put some debug at the top of handleGet though and was not called when the error occurs.

Almost out of ideas now.

@flovilmart
Copy link
Contributor

That may well be the case... we should do the handleMe in the same handler of the objectId

@rgipd
Copy link

rgipd commented Aug 22, 2016

@flovilmart , just a question, this fix is already in 2.2.18 or just in the master commit?
Thank you.

@flovilmart
Copy link
Contributor

Just on master

@rgipd
Copy link

rgipd commented Aug 22, 2016

Ok, thanks.

Just to inform, the error still occurs in master (same code, same error)

error: Uncaught internal server error. [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 (/private/tmp/parse-server-example/node_modules/express/lib/response.js:695:10)
    at allowCrossDomain (/usr/local/lib/node_modules/parse-server/lib/middlewares.js:229:7)
    at Layer.handle [as handle_request] (/usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/layer.js:95:5)
    at next (/usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/route.js:131:13)
    at Route.dispatch (/usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/layer.js:95:5)
    at /usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/index.js:277:22
    at param (/usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/index.js:349:14)
    at param (/usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/index.js:365:14)
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
    at ServerResponse.header (/private/tmp/parse-server-example/node_modules/express/lib/response.js:695:10)
    at ServerResponse.send (/private/tmp/parse-server-example/node_modules/express/lib/response.js:146:12)
    at ServerResponse.json (/private/tmp/parse-server-example/node_modules/express/lib/response.js:235:15)
    at handleParseErrors (/usr/local/lib/node_modules/parse-server/lib/middlewares.js:275:9)
    at Layer.handle_error (/usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/index.js:310:13)
    at /usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/index.js:280:7
    at Function.process_params (/usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/index.js:330:12)
    at next (/usr/local/lib/node_modules/parse-server/node_modules/express/lib/router/index.js:271:10)

@flovilmart
Copy link
Contributor

Which endpoint are you calling?

@rgipd
Copy link

rgipd commented Aug 22, 2016

First I call register

curl -X GET http://localhost:1337/register
app.get('/register', function(req, res) {

 Parse.User.signUp('testuser', 'testpass', {}).then(function (user) {
  console.log('testuser registered with success!');
  res.json({result: 'ok', sessionToken: user.getSessionToken()});
 }); 

});

The output is going to be fine, without errors.
The error appears after, in the:

curl -X GET http://localhost:1337/test2?sessionToken=r:xxxxx
(where r:xxxx is the /register session token output)

with this code:

app.get('/test2', function(req, res) {

 console.log('session token used: ');
 console.log(req.query);

  Parse.Cloud.httpRequest({
   method: 'GET',
   url: 'http://localhost:1337/parse/users/me',
   headers: {
    'X-Parse-Application-Id': 'myAppId',
    'X-Parse-Session-Token': req.query.sessionToken
   }
  }).then(function(userData) {
   res.json({result: 'ok'});
  });

});

P.S.: Even using another nodejs library like request (than Parse.Cloud.httpRequest) the error is the same.

Regards.

@flovilmart
Copy link
Contributor

How you you setup parse-server on the master branch?

@rgipd
Copy link

rgipd commented Aug 22, 2016

With this link: https://github.com/ParsePlatform/parse-server/wiki/Development-Guide

This commands:

git clone https://github.com/ParsePlatform/parse-server.git
npm link parse-server path/to/cloned/repo

I will try another time in other machine.

@flovilmart
Copy link
Contributor

ok... that's odd, I don't have it with the unit tests...

@rgipd
Copy link

rgipd commented Aug 22, 2016

Maybe the problem can be with my machine configuration with npm packages. I couldn't test in another machine.
I will wait for 2.2.19 or next version to make sure it's not my machine (too much dev stuff installed). Or later try in a VM.

Thank you.

@haydenbleasel
Copy link

@flovilmart Sorry if I've missed something in this crazy thread, but I'm getting this on parse-server 2.2.21 and express 4.14.0 when someone tries to log in unsuccessfully:

GET /login 200 36.655 ms - 10457
error: Error generating response. ParseError { code: 101, message: 'Invalid username/password.' } code=101, message=Invalid username/password.
GET /parse/login 404 2639.461 ms - 49
/Users/haydenbleasel/Documents/Projects/test/node_modules/parse-server/lib/ParseServer.js:405
            throw err;
            ^

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
    at ServerResponse.header (/Users/haydenbleasel/Documents/Projects/test/node_modules/express/lib/response.js:719:10)
    at ServerResponse.send (/Users/haydenbleasel/Documents/Projects/test/node_modules/express/lib/response.js:164:12)
    at done (/Users/haydenbleasel/Documents/Projects/test/node_modules/express/lib/response.js:956:10)
    at Immediate._onImmediate (/Users/haydenbleasel/Documents/Projects/test/node_modules/express-handlebars/lib/utils.js:26:13)
    at tryOnImmediate (timers.js:543:15)
    at processImmediate [as _immediateCallback] (timers.js:523:5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:question Support or code-level question
Projects
None yet
Development

No branches or pull requests