can't socket.emit() in Cloud Run server environment - gcloud

My site is using socket.io. Locally it works great. But after deploying with gcloud run deploy the socket.emit() in my javascript file, wont communicate with my app.js file/server.
js file
socket.emit("connectedforrecording");
app.js file
function newConnection(socket) {
console.log("Connection with ID: " + socket.id);
socket.on("connectedforrecording", () => {
console.log("anything??")
// here are connections from /new
console.log("record page", socket.id);
let tempDir ="./tempDirs/temp"+socket.id;
fs.mkdir(tempDir, () => {
fs.chmod(tempDir, "777", () =>{console.log("chmod", tempDir);});
console.log(tempDir);}); // temp dirextory for audio files
var audioReceived = 0;//this flags if writing/written to canvas, so directory is not deleted!
let start = Math.floor(Math.random()*(canvasSize-30)); //start position for recording in secs
console.log(start);
let userdetailsrecieved = 0;
let userDetails = {index: 0, start:0, name:"anonymous", link:"", freq:1000, colour: "#EF863F", sharpness:0.5, sentence:""}; // create a json object with default numbers
userDetails.start = start; // add attribute: start
// request sound from server
socket.on("requestSound", ()=>{
socket.emit("flag", start); // sends start pos to client
sendCanvasSection("./canvas.raw", start, socket);
//////////////////////////////////////n.b. !!!!
// let s = tools.sentence();
let s = sentence();
console.log(s);
console.log("color: ", s.colour);
socket.emit("sentence", s);
// userDetails.colour = {"r":parseInt(hex.slice(1,3), 16), "g":parseInt(hex.slice(3,5), 16), "b":parseInt(hex.slice(5,7), 16)};
userDetails.colour = hexToRgb(s.colour[0]);
userDetails.sharpness = 1- s.angle.v;
userDetails.sentence = s.sentence;
console.log(userDetails);
});
});
});
}

Your question is difficult to answer because you're missing important components of your solution:
Minimally-reproducible example
Explanations of how you deployed to Cloud Run
What you observed, logs and other output
Arbitrary code deployed to Cloud Run cannot be expected to run.
In fact, there's a Cloud Run contract to which code must adhere.
Principally (!), Cloud Run requires a server that listen on (whatever value but generally 8080) is assigned to the PORT environment variable.
WebSockets can be used with Cloud Run services.
Cloud Run provides an in-memory file system (see link) and so you can use Node's fs and can use e.g. fs.mkdir.
Here's my minimally-repro example of a WebSockets solution on Cloud Run that summarizes my attempt to answer your question. I mashed-up Google's WebSockets sample and the intro from Socket.IO
BILLING="[[YOUR-BILLING-ACCOUNT]]"
PROJECT="[[YOUR-PROJECT-ID]]"
REGION="[[YOUR-REGION]]" # e.g. "us-west1"
NAME="[[YOUR-SERVICE]]" # e.g. "websockets"
SERVICES="artifactregistry cloudbuild run"
for SERVICE in ${SERVICES}
do
gcloud services enable ${SERVICE}.googleapis.com \
--project=${PROJECT}
done
gcloud beta run deploy ${NAME} \
--source . \
--allow-unauthenticated \
--region=${REGION} \
--project=${PROJECT} \
--timeout 3600
# Browse
ENDPOINT=$(\
gcloud beta run services describe ${NAME} \
--project=${PROJECT} \
--region=${REGION} \
--format="value(status.url)")
curl --request GET ${ENDPOINT}
I was lazy, the only output is in the client's developer console logs and the server's logs:
FILTER="
resource.type = \"cloud_run_revision\"
resource.labels.service_name = \"${NAME}\"
resource.labels.location = \"${REGION}\"
"
gcloud logging read "${FILTER}" \
--project=${PROJECT} \
--format="value(textPayload)"
Yields:
Listening on 8080
[./tempDirs/templDX9eww0pDOpN63JAAAB] entered
[./tempDirs/templDX9eww0pDOpN63JAAAB] done
[./tempDirs/templDX9eww0pDOpN63JAAAB] chmod
hello from client: 5,6,[object Object]
And the code:
package.json:
{
"name": "websockets",
"version": "0.0.1",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.17.3",
"socket.io": "^4.4.1"
}
}
}
index.js:
// Use server.js
const server = require('./server');
// Cloud Run contract requires server on PORT (or 8080)
const PORT = parseInt(process.env.PORT) || 8080;
server.listen(PORT, () =>
console.log(`Listening on ${PORT}`)
);
process.on('SIGTERM', () => {
process.exit(0);
});
module.exports = server;
server.js:
const express = require('express');
const fs = require('fs')
const app = express();
app.use(express.static(__dirname + '/'));
app.get('/', async (req, res) => {
res.render('index');
});
const server = require('http').Server(app);
const io = require('socket.io')(server);
io.on('connection', socket => {
socket.emit("hello from server", 1, "2", { 3: Buffer.from([4]) });
// Proof of fs
// From your code
let tempDir ="./tempDirs/temp"+socket.id;
fs.mkdir(tempDir, () => {
console.log(`[${tempDir}] entered`);
fs.chmod(tempDir, "777", () =>{
console.log(`[${tempDir}] chmod`);
});
console.log(`[${tempDir}] done`);
});
socket.on("hello from client", (...args) => {
console.log(`hello from client: ${args}`);
});
});
module.exports = server;
index.html:
<html>
<head></head>
<body></body>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io("", {
transports: ["websocket"],
});
socket.emit("hello from client", 5, "6", { 7: Uint8Array.from([8]) });
socket.on("hello from server", (...args) => {
console.log(`hello from server: ${args}`);
});
</script>
</html>

Related

MERN-Stack Heroku - Cannot GET /

Trying to get a MERN-Stack to Deploy on Heroku I've added MONGOBD_URI as a key in Config Vars on Heroku and added the MongoDB Atlas value.
Heroku is connected directly to the Github repo and not through the Heroku CLI. I have it set to auto-deploy but recently redeployed it manually.
This was the Heroku Build Log:
-----> Node.js app detected
-----> Creating runtime environment
NPM_CONFIG_LOGLEVEL=error
NODE_VERBOSE=false
NODE_ENV=production
NODE_MODULES_CACHE=true
-----> Installing binaries
engines.node (package.json): unspecified
engines.npm (package.json): unspecified (use default)
Resolving node version 12.x...
Downloading and installing node 12.20.0...
Using default npm version: 6.14.8
-----> Restoring cache
Cached directories were not restored due to a change in version of node, npm, yarn or stack
Module installation may take longer for this build
-----> Installing dependencies
Installing node modules
> nodemon#2.0.6 postinstall /tmp/build_b41198ca_/node_modules/nodemon
> node bin/postinstall || exit 0
Love nodemon? You can now support the project via the open collective:
> https://opencollective.com/nodemon/donate
added 290 packages in 6.983s
-----> Build
-----> Caching build
- node_modules
-----> Pruning devDependencies
removed 1 package and audited 289 packages in 2.051s
17 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
-----> Build succeeded!
-----> Discovering process types
Procfile declares types -> (none)
Default types for buildpack -> web
-----> Compressing...
Done: 33M
-----> Launching...
Released v17
https://jms-r0b.herokuapp.com/ deployed to Heroku
The browser(Chrome) only renders Cannot GET / and consol.log()'s GET https://jms-r0b.herokuapp.com/ 404 (Not Found) jms-r0b.herokuapp.com/:1
This is the LINK to my repo.
Here's how my server.js is setup:
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const todoRoutes = express.Router();
const PORT = process.env.PORT || 4000;
let Todo = require("./models/todo.model");
app.use(cors());
app.use(bodyParser.json());
// Express data parsing
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("public"));
const URI = process.env.MONGODB_URI || "mongodb://localhost/todos";
mongoose.connect(
URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
},
(err) => console.log(err)
);
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB database connection established successfully");
});
todoRoutes.route("/").get((req, res) => {
Todo.find((err, todos) => {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
todoRoutes.route("/:id").get((req, res) => {
let id = req.params.id;
Todo.findById(id, (err, todo) => {
res.json(todo);
});
});
todoRoutes.route("/update/:id").post((req, res) => {
Todo.findById(req.params.id, (err, todo) => {
if (!todo) {
res.status(404).send("data is not found");
} else {
todo.todo_description = req.body.todo_description;
todo.todo_responsible = req.body.todo_responsible;
todo.todo_priority = req.body.todo_priority;
todo.todo_completed = req.body.todo_completed;
todo
.save()
.then((todo) => {
res.json("Todo updated!");
})
.catch((err) => {
res.status(400).send("Update not possible");
});
}
});
});
todoRoutes.route("/add").post((req, res) => {
let todo = new Todo(req.body);
todo
.save()
.then((todo) => {
res.status(200).json({ todo: "todo added successfully" });
})
.catch((err) => {
res.status(400).send("adding new todo failed");
});
});
todoRoutes.route("/delete/:id").delete((req, res) => {
Todo.findByIdAndRemove(req.params.id, (err, todo) => {
if (!todo) {
res.status(404).send("data is not found");
} else {
res.status(200).json({
msg: todo,
});
}
});
});
app.use("/todos", todoRoutes);
app.listen(PORT, () => {
console.log("http://localhost:" + PORT);
console.log(".env.PORT:" + process.env.PORT);
});
and this is how my root package.json looks:
{
"name": "rob",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start:dev": "cd client && npm start",
"client": "cd client && npm run start",
"start": "concurrently \"node server/server.js\" \"npm run client\"",
"dev": "concurrently \"nodemon server/server.js\" \"npm run client\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/WasteOfADrumBum/r0b.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/WasteOfADrumBum/r0b/issues"
},
"homepage": "https://github.com/WasteOfADrumBum/r0b#readme",
"dependencies": {
"bcryptjs": "^2.4.3",
"concurrently": "^5.3.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-mongo-sanitize": "^2.0.0",
"express-rate-limit": "^5.1.3",
"helmet": "^4.2.0",
"hpp": "^0.2.3",
"ini": "^2.0.0",
"mongoose": "^5.10.13",
"nodemon": "^2.0.6",
"react": "^17.0.1",
"react-cool-onclickoutside": "^1.5.8",
"react-dom": "^17.0.1",
"validator": "^12.0.0",
"xss-clean": "^0.1.1"
},
"devDependencies": {
"dotenv": "^8.2.0"
}
}
I could use a little help. I've deployed 5 other MERN-Stacks with a MongoDB Atlas or JawsDB connection with little to no issues and this one is just throwing me for a loop.
PLEASE HELP!!!
Everyone does things differently, but I think the error is in your connection to MongDB- are you establishing a connection OK or no?
If no connection - You said "I've added MONGOBD_URI as a key in Config Vars on Heroku and added the MongoDB Atlas value." But I see that "config Vars" is not used in your code- you used the .env as you should to keep your connection password secure...so may just need to add your connection URI to the .env file, and you are good to go?
If your connection is fine, then I would look to your server and suggest to test if the problem is solved using the standard routing:
app.route("/")
.get(function(req, res) {
res.sendFile(process.cwd() + "/views/index.html");
})

Error- Warning, FIREBASE_CONFIG environment variable is missing. Initializing firebase-admin will fail

I tried to connect my existing firestore database to Dialogflow fulfillment. The function deployed to Google CLoud Function successfully but I cannot add data to my database. I have tried to change the node version 8 but still failed. Please help me.
Index.js
'use strict';
const admin = require('firebase-admin');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
admin.initializeApp({
apiKey: "Axxxx",
authDomain: "/xxxxx.firebaseio.com",
databaseURL: "https:/xxxxxx.firebaseio.com",
projectId: "mxxxxx8",
storageBucket: "xxxxx.com",
});
const functions = require('firebase-functions');
const settings = {timestampsInSnapshots: true};
var db = admin.firestore();
admin.firestore().settings({ timestampsInSnapshots: true });
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
// intentMap.set('your intent name here', yourFunctionHandler);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
});
package.json
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "8"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "^2.2.0",
"firebase-admin": "~7.1.1",
"firebase-functions": "^2.2.1",
"dialogflow": "^0.6.0",
"dialogflow-fulfillment": "^0.5.0"
}
The solution is upgrade your Firebase project plan to Blaze Plan. Then make a new Dialogflow agent under that Firebase project.
Your Firebase initialization seems wrong. Here's how you should do it:
.
.
.
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
.
.
.
This should work.
Based on the documentation it should be like this,
serviceAccount = require('./serviceAccount.json');
const adminConfig = JSON.parse(process.env.FIREBASE_CONFIG);
adminConfig.credential = admin.credential.cert(serviceAccount);
admin.initializeApp(adminConfig);

Parse Server - Image files' path returns localhost

I have deployed 2 Ubuntu servers on Azure. First, I have installed the Parse Server and the second, I installed MongoDB. (I have also put a ready db there from my previous server via mongorestore)
Everything works fine! Both Parse Server and MongoDB server. They also communicate well. The thing is, when I run my iOS app, it brings all data correctly, except images. I print the URL of an image and here's what it returned: http://localhost:1337/parse/files/filename.jpeg
If I replace localhost with my server's ip, the image is being fetched nicely!
Here's what I have on my index.js:
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var ParseDashboard = require('parse-dashboard');
var allowInsecureHTTP = true;
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://IP:27017/db',
cloud: './cloud/main.js',
appId: process.env.APP_ID || 'xxx',
masterKey: process.env.MASTER_KEY || 'xxx', //Add your master key here. Keep it secret!
fileKey: 'xxx',
serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse', // Don't forget to change to https if needed
// Enable email verification
verifyUserEmails: false,
// The public URL of your app.
// This will appear in the link that is used to verify email addresses and reset passwords.
// Set the mount path as it is in serverURL
publicServerURL: 'http://localhost:1337/parse',
});
// 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();
// 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('Make sure to 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 + '.');
});
// Set up parse dashboard
var config = {
"allowInsecureHTTP": true,
"apps": [
{
"serverURL": "http://localhost:1337/parse",
"appId": "xxx",
"masterKey": "xxx",
"appName": "name",
"production": true
}
],
"users": [
{
"user":"username",
"pass":"pass"
}
]
};
var dashboard = new ParseDashboard(config, config.allowInsecureHTTP);
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.');
});
One thing I noticed at Parse's documentation, is this: When using files on Parse, you will need to use the publicServerURL option in your Parse Server config. This is the URL that files will be accessed from, so it should be a URL that resolves to your Parse Server. Make sure to include your mount point in this URL.
The thing is that this documentation was written having in mind MongoDB, is on the same server with Parse, which in my case isn't.
Any ideas on what to do?
I had to replace the publicServerURL of parse server's config, from http://localhost:1337/parse to http://publicIP:1337/parse and everything worked out great!
If you want to work with files(images) download them, just use publicServerURL as mentioned #Sotiris Kaniras
I would add that the config.json is in ~/stack/parse/config.json. Also here is the difference between serverURL and publicServerURL
Difference between serverURL and publicServerURL on ParseServer
In my case, I needed to add publicServerURL parameter alongside with serverURL because it hasn't existed yet.
So both parameters(publicServerURL & serverURL) are complement, not mutually exclusive, use them both.

How to set options for json-server as a module?

Suppose we have the following command line to run a json-server (https://github.com/typicode/json-server):
json-server db.json --routes routes.json --port 8008 --delay 1000
If we were to run json-server as a module, how do we set these options? I can see the db.json defined and the port defined. But it is not clear how the rest of the options can be defined.
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middleWares = jsonServer.defaults();
server.use(middleWares);
router.render = (req, res) => {
console.log(req);
};
server.use(router);
server.listen(8008, () => {
console.log('JSON Server is running');
});
I found how to set the delay. This requires installing the connect-pause package, which is also used in the json-server code (https://www.npmjs.com/package/connect-pause):
npm install connect-pause
Then on the server.js file, I added the following a require('connect-pause') and used it in the json server app. Here is my code:
const fs = require('fs');
const pause = require('connect-pause');
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
server.use(middlewares);
server.use(jsonServer.bodyParser);
//
// Define custom routes (routes.json)
//
var routes = JSON.parse(fs.readFileSync('routes.json'));
server.use(jsonServer.rewriter(routes));
...
server.use(pause(1000));
server.use(router);
server.listen(8008, () => {
console.log('JSON Server is running');
});
To set any other option varies wildly, but I mainly needed to know how to set the delay.

"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 :
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.
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...