Using Parse Javascript SDK in express app with Parse-Server - javascript

I have a node.js express app using the Parse Javascript SDK and Parse-Server.
I've set everything up according to the guide but the JS SDK is not working.
I'm getting {error:unauthorized}. I can access my server with REST API just fine but not from within the app using the JS SDK.
I read that you have to specify useMasterKey = true for all operations with Parse-Server so:
var User = Parse.Object.extend('_User');
var query = new Parse.Query(User);
query.useMasterKey = true;
query.find().then( function(results) {
console.log(results);
},
function(error) {
console.log(JSON.stringify(error));
});
Should return the same data that this curl does (right?):
curl -X GET \
-H "X-Parse-Application-Id: myAppId" \
-H "X-Parse-Master-Key: myMasterKey" \
http://localhost:1337/parse/classes/_User
Alas, this is not the case.
Same error message when I try to run the default cloud code function:
Parse.Cloud.run('hello').then( function(response) {
console.log(response);
},
function(error) {
console.log(JSON.stringify(error));
});
Any ideas that might help? Thanks.

Got it!
What did it for me were these lines in my Express app
var Parse = require('parse/node').Parse;
Parse.initialize('app_id', 'js_key','master_key');
Parse.serverURL = 'serverURL';
Parse.Cloud.useMasterKey();
After these lines, any kind of call that requires Cloud Code usage or Parse usage were authorized

My problem was inexperience:
I am using body-parser and had the app set up to use that module's raw, json, text, and urlencoded middleware functions.
I only needed the urlencoded option. I removed the others and the JS SDK started working fine. Somehow, the other functions were interfering with the SDK.

Related

How to use curl with superagent/fetch in javascript

I am trying to wire up my app to an external api. The external api's documentation says to make the call using curl:
curl "https://wordsapiv1.p.mashape.com/words/soliloquy"
-H "X-Mashape-Key: <required>"
My app is built with JS/React - I am unfamiliar with the above syntax. I am trying to figure out how to write this using superagent (or, if necessary, fetch).
This is what I have so far from following some other SO answers but I have no idea how to incorporate: -H "X-Mashape-Key: <required>"
My api key is stored in a .env file.
require('dotenv').config
console.log(process.env)
const request = require('superagent')
const url = 'https://wordsapiv1.p.mashape.com/words/'
//dictionary
export function getDictionaryDefinition(word) {
return request.get(`${url}/dog`).then((response) => {
console.log(response)
})
}
I highly recommend getting familiar with the basics of curl. It's worth knowing and it's everywhere. you can find nice cheat sheets here and here.
-H in curl represent a header, so in your case you'll need to add that to your request, e.g.
request.get(`${url}/dog`)
.set('X-Mashape-Key', API_KEY)
.then((response) => {...
or in fetch:
fetch("https://wordsapiv1.p.mashape.com/words/soliloquy", {
headers: {
"X-Mashape-Key": API_KEY
}
})
as a bonus, I found a nice project that "translates" curl to fetch: https://kigiri.github.io/fetch/

Node.js JavaScript Basic Get Request

Just installed node.js, and I'm having trouble sending basic get requests. I used to run things in chrome/firefox's console but wanted to branch out. What I am trying to do (as a test) is send a get request to a webpage, and have it print out some text on it.
In chrome's console, I would do something like this:
$.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(data) {
console.log($(data).find(".question-hyperlink")[0].innerHTML);
});
In node.js, how would I do that? I've tried requiring a few things and gone off a few examples but none of them worked.
Later on, I'll also need to add parameters to get and post requests, so if that involves something different, could you show how to send the request with the parameters {"dog":"bark"}? And say it returned the JSON {"cat":"meow"}, how would I read/get that?
You can install the request module with:
npm install request
And, then do this in your node.js code:
const request = require('request');
request.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(err, response, body) {
if (err) {
// deal with error here
} else {
// you can access the body parameter here to see the HTML
console.log(body);
}
});
The request module supports all sorts of optional parameters you can specify as part of your request for everything from custom headers to authentication to query parameters. You can see how to do all those things in the doc.
If you want to parse and search the HTML with a DOM like interface, you can use the cheerio module.
npm install request
npm install cheerio
And, then use this code:
const request = require('request');
const cheerio = require('cheerio');
request.get("http://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js", function(err, response, body) {
if (err) {
// deal with error here
} else {
// you can access the body parameter here to see the HTML
let $ = cheerio.load(body);
console.log($.find(".question-hyperlink").html());
}
});

database node.js to angularjs

I am new to Node.JS and AngularJS and I have made a connection to a database using Node.js (code below)
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodetest'
});
connection.connect();
connection.query('SELECT * from testtable', function(err, rows, fields) {
if (!err) {
var test = rows;
console.log('The solution is: ', test);
return test;
} else{
console.log('Error while performing Query.');
}
});
connection.end();
the database consists of 2 tables (ID and name) and only has 1 row (1, 'Luuk')
my code gets put through Grunt for compiling.
when I run the script stated above, it give the expected result (The solution is: [ RowDataPacket { ID: 1, name: 'Luuk' } ])
but when I want to add this to a controller in angularjs, it gives no results
app.controller('NameController', function() {
this.nameList = test;
});
how would be fixed?
I think that you're confusing concepts.
Angular.js and Node.js are running in a COMPLETELY different environment. Node.js is a server, that is running locally in your machine, which you can access via browser with the url localhost:3000 for example. But this server can be running on another machine for example, which you would be able to access via IP, something like 123.4.5.678:3000.
To share data between the backend and the frontend, you must do this over requests. When you access the localhost via browser, you're doing a request to the server, and the server provide some response, like a HTML page or something like that.
Look this example at the Nodejs Docs
http.createServer( function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(3000);
In the response we are returning a plain text. But this can be json, with your search at the database.
And you can do a specific route, like /getTestTable which you can call in the Angular, with the $http service, and handle this.
I suggest to take a better look at how Node.js works, and Angular.js too.
You would like to take a look too at the Express.js, a framework for Node.
Check the scope of variable test - it is defined inside call back function of connection.query. Try defining variable 'test' globally.

AngularJS API call error with $http GET

I'm trying to create a simple app using Angular that will consume my API. I'm using a VM to run the code, and I access it on my computer, so to call the API from my machine I can use cURL or any other HTTP client and everything works. An example:
curl -k --user damien#email.com:password https://api.my.domain.com/v1/traveler/get
And that would return a list of travelers for example. I need to "trust" the certificate as it is not valid. So on the browser at first the call would return net::ERR_INSECURE_RESPONSE, so I'm just going to the API URL and add the exception and now I don't have this issue anymore. Then I had to add basic authentication, and it seems to work. Let's see what is my code and please let me know if you see anything wrong, I'm following this tutorial that consume an external API: http://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app
app.js:
angular.module('TravelerApp', [
'TravelerApp.controllers',
'TravelerApp.services'
]);
services.js:
angular.module('TravelerApp.services', [])
.factory('TravelerAPIService', function($http) {
var travelerAPI = {};
$http.defaults.headers.common.Authorization = 'Basic ABC743HFEd...=';
travelerAPI.getTravelers = function() {
return $http({
method: 'GET',
url: 'https://api.my.domain.com/v1/traveler/get'
});
}
return travelerAPI;
});
Finally, the controllers.js:
angular.module('TravelerApp.controllers', [])
.controller('travelersController', function($scope, TravelerAPIService) {
$scope.travelersList = [];
TravelerAPIService.getTravelers()
.success(function(data) {
console.log('SUCCESS');
$scope.travelersList = data;
})
.error(function(data, status) {
console.log('ERROR');
$scope.data = data || "Request failed";
$scope.status = status;
});
});
The error status code is 0, and the error data is an empty string.
Precisions:
I have the same behavior with an HTTP POST query.
I am sure :
no request have been made on the server
it's angular that don't sent the query
And finally I find the answer:
Since I (and probably you) are sending on a self signed httpS server. Chrome flag it as none safe.
I fix this issue by putting the address on my browser and manually accept the certificate.
Probably related : XMLHttpRequest to a HTTPS URL with a self-signed certificate
I would suggest to use Trusted CA Signed SSL Certificate rather then Self-Signed Certificates which would solve your problem as most browsers do not accept the self signed certificates like Google Chrome,Firefox,etc.

Starting with Node.js and CouchDB without libraries like nano or cradle [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Getting ' bad_request invalid_json' error when trying to insert document into CouchDB from Node.js
The highest voted answer on
CouchDB and Node.js - What module do you recommend?
recommends not to use libraries such as nano or cradle for starting with Node.js and CouchDB.
However I haven't found any tutorial on how to perform standard operations for all DBMSes like create database, create table, add and view data etc. programmatically.
EDIT: (partial answer) after installing and starting CouchDB go to http://localhost:5984/_utils/script/couch.js.
You should start by reading the CouchDB book.
No idea why you don't want to use a module: I think you took an answer out of context (an answer that is probably one year old) and made your decision not to use a module.
That is not likely to be helpful to get stuff done. :) You are just repeating work that is done, and issues that have been fixed, etc.
If you want to learn CouchDB, read the book. You can read nano's source as it maps really closely to the API and should be easy to read, but the book is the full way to go.
If by any reason you decide you still want to implement your own module to do what others already do well, go for it :)
If instead you are looking for resources on using nano there are quite a few:
readme: github
screencast: couchdb and nano
article: nano - a minimalistic couchdb client for nodejs
article: getting started with node.js and couchdb
article: document update handler support
article: nano 3
article: securing a site with couchdb cookie authentication using node.js and nano
article: adding copy to nano
article: how to update a document with nano
article: mock http integration testing in node.js using nock and specify
article: mock testing couchdb in node.js with nock and tap
Thanks to Ruben Verborgh, I compiled micro-tutorial from several sources myself.
var http = require('http')
var sys = require('sys')
var couchdbPath = 'http://localhost:5984/'
request = require('request')
h = {accept: 'application/json', 'content-type': 'application/json'}
request(
{uri: couchdbPath + '_all_dbs', headers:h},
function(err, response, body) { console.log(sys.inspect(JSON.parse(body))); }
)
// add database
request(
{uri: couchdbPath + 'dbname', method:'PUT', headers:h},
function (err, response, body) {
if (err)
throw err;
if (response.statusCode !== 201)
throw new Error("Could not create database. " + body);
}
)
// Modify existing document
var options = {
host: "localhost",
port: 5984,
path: "/dbname",
headers: {"content-type": "application/json"},
method: "PUT"
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
//console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(JSON.stringify({
"_id":"rabbit",
"_rev":"4-8cee219da7e61616b7ab22c3614b9526",
"Subject":"I like Plankton"
}));
req.end();
I used following documentation:
http.request()
CouchDB Complete HTTP API Reference
Here are a few hands-on examples, thoughts and code-snippets which should help in your study
Simple Blog with Coffeescript, Express and CoudbDB
Thoughts on development using CouchDB and Nodejs
Bind CouchDB and Node.js
Getting Started with Node.js, Express and CouchDB - this link does not seem to be accessible now, but it seems a temporary issue.
Here's one on testing CouchDB - Mock testing CouchDB using Node.js
Hope it helps.
CouchDB is not an SQL database engine. It's in the family of the "NoSQL" ones.
You don't do select, you don't create tables, etc.
It's completely different.
It's actually using a REST API to work. Like, to access all the documents, you access them using an HTTP GET on the following URL: http://some.server/someDbName/_all_docs
For a more thorough introduction, I suggest looking for "CouchDB tutorial" on Google.
You'll find good links like this one or this one. (I'm not vouching for any, they just look good as an introduction.)
To make an http request in node.js, you can use the request method of the built-in http module. A shortcut method is http.get, which you can use like this:
var http = require( 'http' );
http.get( 'http://some.url/with/params', function( res ) {
// res has the values returned
});
Edit after reading your code:
Firstly, the doc you're using if outdated. Node is at v0.8, not 0.4.
Secondly, your request = require('request') must give some problems (does the module exist?). I don't think the first part is even executed.
Thirdly, just try a GET request for now. Something like:
var http = require( 'http' );
http.get( 'http://localhost:5984/_all_dbs', function( res ) {
console.log( res );
});
See if it's working. If it is, you already know how to use couchdb ;)
Lastly, your request at the end doesn't seem wrong. Maybe it's related to require('request') though, so I don't know.

Categories