parse-community / parse-server-push-adapter

A push notification adapter for Parse Server
https://parseplatform.org
MIT License
85 stars 100 forks source link

#### PUSH ERRORReceived an error with invalid JSON from Parse #102

Open monajafi opened 6 years ago

monajafi commented 6 years ago

Hi After successful push send the following error prevents push to be sent:

0|parse-wr | #### PUSH ERRORReceived an error with invalid JSON from Parse: <html>
0|parse-wr | <head><title>400 Bad Request</title></head>
0|parse-wr | <body bgcolor="white">
0|parse-wr | <center><h1>400 Bad Request</h1></center>
0|parse-wr | <hr><center>nginx/1.10.3 (Ubuntu)</center>
0|parse-wr | </body>
0|parse-wr | </html>

This happened after I changed my ubuntu server DNS here is my nginx sites-enabled/default

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;
        root /mnt/psapp/;
        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name psappco.ir www.psappco.ir;

        location / {
           try_files $uri $uri/ =404;
         }
        # location /test {
          # root /mnt/psapp;
        # }
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php7.0-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php7.0-fpm:
        #       fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/psappco.ir/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/psappco.ir/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    # Redirect non-https traffic to https
    # if ($scheme != "https") {
    #     return 301 https://$host$request_uri;
    # } # managed by Certbot
    location /parse/ {
 proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-NginX-Proxy true;
                proxy_pass http://localhost:1337/parse/;
                proxy_ssl_session_reuse off;
                proxy_set_header Host $http_host;
                proxy_redirect off;
                # WebSocket support
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }
        location /dashboard/ {
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header X-NginX-Proxy true;
         proxy_pass http://localhost:4040/dashboard/;
         proxy_ssl_session_reuse off;
         proxy_set_header Host $http_host;
         proxy_redirect off;
        }
        client_max_body_size 100M;
}

should I add something related to push adapter in nginx ,I 've activated ssl using lets encrypt. nginx version: nginx/1.10.3 (Ubuntu) parse-server version 2.3.8 cloud code which I've used is:

Parse.Cloud.define('driveRequest', function(request, response) {
    // request has 2 parameters: params passed by the client and the authorized user
    var params = request.params;
    var user = request.user;
    // extract out the channel to send
    var action = params.action;
    var launch = params.launch;
    // use to custom tweak whatever payload you wish to send
    var pushQuery = new Parse.Query(Parse.Installation);
    var driverQuery = new Parse.Query(Parse.User);
    driverQuery.equalTo("isonline",true);
    driverQuery.equalTo("riderordriver","driver");
    //var nearbyDriversQuery = new Parse.Query(Parse.User);
    var riderLocation = new Parse.GeoPoint({latitude: params.riderLatitude, longitude: params.riderLongitude});
    driverQuery.withinKilometers("location",riderLocation,2.0);
    //var driverQuery = Parse.Query.or(nearbyDriversQuery,isOnlineQuery);
    pushQuery.matchesQuery('users',driverQuery);
   // pushQuery.matchesQuery('isonlineusers',isOnlineQuery);
    var payload = {
        "action": action,
        "launch": launch,
    };

    // Note that useMasterKey is necessary for Push notifications to succeed.

    Parse.Push.send({
        where: pushQuery,
        data: payload
    }, { success: function() {
        console.log("#### PUSH OK");
    }, error: function(error) {
        console.log("#### PUSH ERROR" + error.message);
    },useMasterKey:true});
    response.success('success');
});

And ParseServer index.js:

var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var ParseDashboard = require('parse-dashboard');  
var path = require('path');
var FSStoreAdapter = require('parse-server-fs-store-adapter');
var fs_store_adapter = new FSStoreAdapter({
    filesSubDirectory: "/root/parsefiles" 
});
//var Parse = require('parse/node').Parse;

var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;

if (!databaseUri) {
  console.log('DATABASE_URI not specified, falling back to localhost.');
}

var pushConfig = {};

if (process.env.GCM_SENDER_ID && process.env.GCM_API_KEY) {
    pushConfig['android'] = { senderId: process.env.GCM_SENDER_ID || 'my sender id',
                              apiKey: process.env.GCM_API_KEY || 'my key'};
}

var api = new ParseServer({
  databaseURI: databaseUri || 'mongodb://localhost:27017/taxifinder',
  cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
  appId: process.env.APP_ID || 'My app_ID',
  masterKey: process.env.MASTER_KEY || 'My master key', //Add your master key here. Keep it secret!
  push: pushConfig,
  filesAdapter: fs_store_adapter,
  serverURL: process.env.SERVER_URL || 'https/localhost:1337/parse',  // Don't forget to change to https if needed
  liveQuery: {
    classNames: ['Test'],
    redisURL: 'redis://localhost:6379'
  },
  maxUploadSize: "100mb"
});
var app = express();
// 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!');
//      res.sendFile(path.join(__dirname, '/public/index.html'));
//});

// There will be a test page available on the /test path of your server url
// Remove this before launching your app
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
    console.log('parse-server-example running on port ' + port + '.');
});
ParseServer.createLiveQueryServer(httpServer,{
        redisURL: 'redis://localhost:6379'
});

var dashboard = new ParseDashboard({  
  "apps": [{
      "serverURL": 'https://psappco.ir/parse', // Not localhost
      "appId": 'my app id',
      "masterKey": 'My master key',
      "appName": "PSAPP",
      "production": false,
      "iconName": "app-icon.png",
  }],
  "users": [
    {
      "user":"---",
      "pass":"----"
    }
  ],
  "iconsFolder": "icons"
});

var dashApp = express();

// make the Parse Dashboard available at /dashboard
dashApp.use('/dashboard', dashboard);  

// Parse Server plays nicely with the rest of your web routes
dashApp.get('/', function(req, res) {  
  res.status(200).send('Parse Dashboard App');
});

var httpServerDash = require('http').createServer(dashApp);  
httpServerDash.listen(4040, function() {  
    console.log('dashboard-server running on port 4040.');
});
flovilmart commented 6 years ago

Can you update parse-server to the latest version?

monajafi commented 6 years ago

Hi mr flovilmart I've installed parse-server-example on ubuntu server also mongodb is on the same machine I fear of losing data but I have to try already it was working just aftet updating nginx and changing dns on bind9 , reinstalling ssl certificate and rebooting system this error happened I really get stuck on this i will try and respond here Thanks

monajafi commented 6 years ago

Should i update parse-server-push-adapter seperately or parse server update will update that too?

monajafi commented 6 years ago

Hi Mr Vilmart I've updated parse-server and parse-server-push-adapter to the latest version but still same error happened. I doubted on GCM api key and senderId also nginx configuration. I am getting really mad because my customer getting mad the project was running already now stopped because of this error. please help me

flovilmart commented 6 years ago

This happened after I changed my ubuntu server DNS here is my nginx sites-enabled/default

You should probably revert back to a previous version of your configuration. It's unlikely unrelated to parse-server itself.

Can you check your nginx logs to see what call would make that error? Did you configure your serverURL properly?

monajafi commented 6 years ago

This error comes from Parse.Push.send method as following

Parse.Push.send({
        where: pushQuery,
        data: payload
    }, { success: function() {
        console.log("#### PUSH OK");
    }, error: function(error) {
        console.log("#### PUSH ERROR" + error.message);
    },useMasterKey:true});
    response.success('success');

about serverUrl every function like Object saving Querying in parse and parse dashboard are working just push is not working also this warning is shown after running cloud code

WARNING, Unable to connect to 'http/localhost:1337/parse'. Cloud code and push notifications may be unavailable!

this is my index.js serverUrl:

serverURL: process.env.SERVER_URL || 'http/localhost:1337/parse'

and nginx config:

location /parse/ {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-NginX-Proxy true;
                proxy_pass http://localhost:1337/parse/;
                proxy_ssl_session_reuse off;
                proxy_set_header Host $http_host;
                proxy_redirect off;
                # WebSocket support
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }
monajafi commented 6 years ago

Hi I've found the root cause of 400 Bad Request. I wrote a simple query and object sample code in cloud code which can not run by this error:

0|parse-wr | verbose: RESPONSE from [POST] /parse/classes/Trip: {
0|parse-wr |   "status": 201,
0|parse-wr |   "response": {
0|parse-wr |     "objectId": "JUW8KIpyCK",
0|parse-wr |     "createdAt": "2017-12-08T11:05:56.741Z"
0|parse-wr |   },
0|parse-wr |   "location": "http://psappco.ir/parse/classes/Trip/JUW8KIpyCK"
0|parse-wr | } status=201, objectId=JUW8KIpyCK, createdAt=2017-12-08T11:05:56.741Z, location=http://psappco.ir/parse/classes/Trip/JUW8KIpyCK
1|parse-wr | verbose: REQUEST for [POST] /parse/functions/driveRequest: {
1|parse-wr |   "riderLongitude": 49.187789261341095,
1|parse-wr |   "riderLatitude": 30.716097895513627,
1|parse-wr |   "tripId": "JUW8KIpyCK"
1|parse-wr | } method=POST, url=/parse/functions/driveRequest, x-real-ip=5.215.157.80, x-forwarded-for=5.215.157.80, x-nginx-proxy=true, host=psappco.ir, connection=upgrade, content-length=94, x-parse-session-token=r:72ae786ff94369a24ea262be3fa5e032, x-parse-application-id=f94ca623-4b36-4f0b-8705-228eefa7e4e0, x-parse-client-version=a1.16.3, x-parse-app-build-version=2, x-parse-app-display-version=1.0.2, x-parse-os-version=7.0, user-agent=Parse Android SDK 1.16.3 (ir.psappco.psapp/2) API Level 24, x-parse-installation-id=ccacc4fa-68ed-44cf-bf99-04a4457a9629, content-type=application/json, accept-encoding=gzip, riderLongitude=49.187789261341095, riderLatitude=30.716097895513627, tripId=JUW8KIpyCK
1|parse-wr | error: Failed running cloud function driveRequest for user lPHtBbLm7D with:
1|parse-wr |   Input: {"riderLongitude":49.187789261341095,"riderLatitude":30.716097895513627,"tripId":"JUW8KIpyCK"}
1|parse-wr |   Error: {"code":141,"message":"Received an error with invalid JSON from Parse: <html>\r\n<head><title>400 Bad Request</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>400 Bad Request</h1></center>\r\n<hr><center>nginx/1.10.3 

this already reported here too without proper response: https://github.com/parse-community/parse-server/issues/2190 my node version 9.2.0 npm version 5.5.6 parse server 2.7.1