I want to store some user values, name and email, in a Postgres DB on an app hosted by Heroku. This is the code in my controller;
var pg = require('pg');
...
$scope.addUser = function() {
pg.connect(process.env.DATABASE_URL, function(err, client) {
var query = client.query('INSERT INTO users (name, email) VALUES (\'' + $scope.user.name + '\', \'' + $scope.user.email + '\')');
query.on('row', function(row) {
console.log(JSON.stringify(row));
});
});
};
I get an error saying that require is not defined, which I know is because it is not supported client side. I tried using browserify on the controller file, then updating the <script> tag in the index.html that sources the file. This leads to another error.
Removing the var pg = require('pg'); gives a "ReferenceError: pg is not defined". I just want to connect to the Postgres DB from my app and insert some values. Am I on the right track or should I be going about this differently?
See Can I use PostgreSQL (pg) in the client-side (express/node.js) as to why you can't let clients connect directly to your database. You either want to write a (lightweight) server app (probably using Node.js), or you should consider a backend-as-a-service (BaaS) like Firebase or IrisCouch so that you don't need to develop the backend at all.
Related
I'm trying to write a simple rest API to connect to my sql Server database and execute a simple query to retrieve data from a database.
I'm following this tutorial: https://medium.com/voobans-tech-stories/how-to-quickly-create-a-simple-rest-api-for-sql-server-database-7ddb595f751a
Here's where my confusion lies:
The example has a server initialization file that looks like this:
var express = require('express'); // Web Framework
var app = express();
var sql = require('mssql'); // MS Sql Server client
// Connection string parameters.
var sqlConfig = {
user: 'UserName',
password: 'mot de passe',
server: 'localhost',
database: 'DatabaseName'
}
// Start server and listen on http://localhost:8081/
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("app listening at http://%s:%s", host, port)
});
It also has a select query the example uses on the customer table located in the database:
app.get('/customers', function (req, res) {
sql.connect(sqlConfig, function() {
var request = new sql.Request();
request.query('select * from Sales.Customer', function(err, recordset) {
if(err) console.log(err);
res.end(JSON.stringify(recordset)); // Result in JSON format
});
});
})
What I'm not understanding is how these two files are connected or interacting. At the end of the tutorial, the author says in order to test the example, copy the code into a file and run it. The example has 4 separate files though - am I putting them all into the same document?
yes you can put all code snippets in the same file for your test. It will be the easiest way since they all using the app variable.
But if you want a bigger application, it's cleaner in multiple files. You can then use code from another file using an import like require('./filename.js');
I'm practicing right now with the MEAN stack.
I've made a project with the Angular shell and I've inclueded express in my project.
Here's my first GET, i want to use it to retrive some data from my mongoDB, in this case an entire collection:
router.get('/biscottigrazie', function(req, res) {
var db = req.db;
var collection = db.get('biscotti');
});
Maybe I'm missing the concept but i think that from angular i should be able to "call" this GET and get the data.
So, my var collection should contain the data, how can I retrive them from angular files?
You will not get db instance from request variable. You will get it while you define database.
var db = new Db('test', new Server('localhost', 27017));
router.get('/biscottigrazie', function(req, res) {
var collection = db.getCollection('biscotti');
res.send(collection);
});
I have created an MVC website in vb.NET which runs perfectly well on the local server.
I have published it to a remote server using the Publish method of Visual Studio so I believe all the necessary files should be in place on the remote server. The web hosting service runs MVC 4 and 5. On running the page from the remote server the AngularJS code fails to find the VB controller.
In the AngularJS Service section the code is:
this.getPasswords = function () {
return $http.get("api/passwords");
};
In the AngularJS controller section the relevant code is:
getPasswords();
// get from passwordsController.vb
function getPasswords() {
passwordService.getPasswords()
.success(function (passwords) {
$scope.passwords = passwords;
})
.error(function (error) {
$scope.status = 'Error in getting passwords: ' + error.message;
});
};
The VB controller code is:
' GET: api/passwords
Function Getpasswords() As IQueryable(Of password)
Return db.passwords
End Function
The line:
return $http.get("api/passwords");
does not connect with the Getpasswords function in the VB controller.
Any help would be much appreciated.
Most likely, it's a URL issue. You're calling api/passwords, which will be relative to whatever basepath is in play. For example, if you're on a URL already, like http://example.com/foo/bar, then the URL you're actually requesting is http://example.com/foo/bar/api/passwords, which is almost certainly not correct. You should always use paths like /api/passwords. The preceding / causes the URL to be domain-relative, i.e. http://example.com/api/passwords.
I just started to build a web app, and for some reason I have to use CloudKit and its database for my backend.
I tried a really stupid database query and intended to see the results at frontend. Here is my code :
CloudKit.configure({
containers: [{
containerIdentifier: my identifier,
apiToken: my api token,
environment: 'development'
}]
});
var container = CloudKit.getDefaultContainer();
var DB = container.publicCloudDatabase;
var query = {recordType : 'Request'};
DB.performQuery(query).then(function(response){
if (response.hasErrors) {
throw response.errors[0];
} else {
console.log(response);
}
});
However, I keep getting this authentication_failed error :
cloudkit.js:3 Uncaught (in promise) t {_ckErrorCode: "AUTHENTICATION_FAILED", _uuid: "4ef8ba12-eb00-408f-9a1c-6e8b4de84ec8", _reason: "no auth method found", _serverErrorCode: "AUTHENTICATION_FAILED", _extensionErrorCode: undefined…}
I tried to fetch a record with the same code, and it works fine.
So is the error caused by unlogged in users? If so, Is there any configurations in CloudKit Dashboard to allow users from certain URL to query the database without logging in?
Thanks!
Check the containerIdentifier value. I had a similar issue when I used the identifier name of the API Token instead of the generated iCloud identifier from the app name. You can also verify your token with the link Test with CloudKit Catalog
So I have this web-app using angularJS and nodeJS. I don't want to just use localhost to demo my project because it doesn't looks cool at all when I type "node server.js" and then go to localhost.....
Since I intend to use Firebase for the data, I have noticed that Firebase provides hosting. I tried it, but it seems to only host the index.html and not through/using server.js. I have customized files for the server to use/update. So, how can I tell Firebase Hosting to use my server and related files when hosting?
Is it possible to tell Firebase, hey, run "node server.js" to host my index.html?
I'm guessing by the way you are wording the question you want to see this site from "the internet".
Two routes you could go here.
a) Serve your index through Firebase hosting. Firebase only hosts assets. If your Angular app is being served through Node then you will need to change your architecture to be more SPA-ish
SPA-ish would be like an index bootstrap that interacts with the backend purely through API's.
You would host the API server on something more appropriate like through Nodejitsu.
b) Serve the whole thing through something like Nodejitsu (hosting platform) or your very own VM managed by a different kind of hosting company like BuyVM.net.
Another idea, is if your nodejs app is independent of the angularjs app (however they use shared data, and perform operations on that data model) you could separate the two and connect them only via firebase.
Firebase hosting -> index.html and necessary angularjs files.
Locally (your PC) -> server.js which just connects to firebase and trigger on changed data.
I have done this for a few projects and it's a handy way to access the outside world (internet) while maintaining some semblence of security by not opening ports blindly.
I was able to do this to control a chromecast at my house while at a friends house
Here's an example from my most recent project (I'm trying to make a DVR).
https://github.com/onaclov2000/webdvr/blob/master/app.js
var FB_URL = '';
var Firebase = require('firebase');
var os = require('os')
var myRootRef = new Firebase(FB_URL);
var interfaces = os.networkInterfaces();
var addresses = [];
for (k in interfaces) {
for (k2 in interfaces[k]) {
var address = interfaces[k][k2];
if (address.family == 'IPv4' && !address.internal) {
addresses.push(address.address)
}
}
}
// Push my IP to firebase
// Perhaps a common "devices" location would be handy
var ipRef = myRootRef.push({
"type": "local",
"ip": addresses[0]
});
myRootRef.on('child_changed', function(childSnapshot, prevChildName) {
// code to handle child data changes.
var data = childSnapshot.val();
var localref = childSnapshot.ref();
if (data["commanded"] == "new") {
console.log("New Schedule Added");
var schedule = require('node-schedule');
var date = new Date(data["year"], data["month"], data["day"], data["hh"], data["mm"], 0);
console.log(date);
var j = schedule.scheduleJob(date, function(channel, program, length){
console.log("Recording Channel " + channel + " and program " + program + " for " + length + "ms");
}.bind(null, data["channel"], data["program"], data["length"]));
localref.update({"commanded" : "waiting"});
}
});
When I change my "commanded" data at the FB_URL, to "new" (which can be accomplished by angularjs VERY Simply, using an ng-click operation for example) it'll schedule a recording for a particular date and time (not all actually functional at the moment).
I might be late but since 3 years have passed there is an solution available now from Firebase in the form of cloud functions
Its not straight forward but looks promising if one can refactor their code a bit