Search code examples
mongodbherokuparse-platformparse-server

"Unable to connect to the Parse API" using Parse Server on Heroku


I'm getting the error Failed to create new object, with error code: XMLHttpRequest failed: "Unable to connect to the Parse API" when i try to connect to Parse Server API. I deployed ParsePlatform/parse-server-example on Heroku. I can access to my app with a broswser with no problems.I get the error when trying to connect to Parse on Heroku with this code :

var $result=$('#results').html('Testing configuration.....');
  Parse.initialize('<MY_APP_ID>', '<MY_JAVASRIPT_KEY>');
  Parse.serverURL = '<MY_HEROKU_APP_NAME>.herokuapp.com/'

  var ParseServerTest = Parse.Object.extend('ParseServerTest');
  var _ParseServerTest = new ParseServerTest();

  _ParseServerTest.set('key', 'value');
  _ParseServerTest.save(null, {
    success: function(_ParseServerTest) {
      var txt = 'Yay, your server works! New object created with objectId: ' + _ParseServerTest.id;
      $result.html('<div class="alert alert-success" role="alert">' + txt + '</div>');
    },
    error: function(_ParseServerTest, error) {
      var txt = 'Bummer, Failed to create new object, with error code: ' + error.message;
      $result.html('<div class="alert alert-danger" role="alert">' + txt + '</div>');
    }
  });

index.js

// Example express application adding the parse-server module to expose Parse
// compatible API routes.

var express = require('express');
var cors = require('cors');

var ParseServer = require('parse-server').ParseServer;
var path = require('path');

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

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

var api = new ParseServer({
  databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
  cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
  appId: process.env.APP_ID || 'myAppId',
  masterKey: process.env.MASTER_KEY || '', //Add your master key here. Keep it secret!
  serverURL: process.env.SERVER_URL || 'https://localhost:1337/parse',  // Don't forget to change to https if needed
  liveQuery: {
    classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
  }
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey

var app = express();
app.use(cors());

// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));

// 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'));
});

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 + '.');
});

// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);

Heroku config :

Heroku config

I followed this post : How can I host my own Parse Server on Heroku using MongoDB? except i didn't use the "Deploy to Eroku" button, i deployed it manually.

Thank you for your help.


Solution

  • Finally I found a way. I first created another user in my mongo db and change it in Heroku. Try to connect with the same js code code jsfiddle but didn't work...

    Then I tried with an android client, this link helped me a lot http://www.robpercival.co.uk/parse-server-on-heroku/

    StarterApplication.java

    public class StarterApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
    
        // Enable Local Datastore.
        Parse.enableLocalDatastore(this);
    
        // Add your initialization code here
        Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
                .applicationId("BUTYcVjD7nFz4Le")
                .clientKey("XgQaeDY8Bfvw2r8vKCW")
                .server("https://xxxxx-xxxx-xxxxx.herokuapp.com/parse")
                .build()
        );
    
        ParseUser.enableAutomaticUser();
        ParseACL defaultACL = new ParseACL();
        // Optionally enable public read access.
        // defaultACL.setPublicReadAccess(true);
        ParseACL.setDefaultACL(defaultACL, true);
    }
    

    MainActivity.java

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    
        ParseAnalytics.trackAppOpenedInBackground(getIntent());
    
        ParseObject test = new ParseObject("Test");
        test.put("username","pedro");
        test.put("age",33);
        test.saveInBackground(new SaveCallback() {
            public void done(ParseException e) {
                if (e == null) {
                    Log.i("Parse", "Save Succeeded");
                } else {
                    Log.e("Parse", "Save Failed");
                }
            }
        });
    
    }
    

    I really don't know what was the problem with my first user, can't connect with it. I never could connect with the js code... but anyway my goal was to connect with Android client so...