postgresql 如何从 angularjs 控制器连接到 postgres 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23231316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:25:13  来源:igfitidea点击:

How to Connect to postgres db from angularjs controller

angularjspostgresqlheroku

提问by mattr

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;

我想在 Heroku 托管的应用程序上的 Postgres 数据库中存储一些用户值、姓名和电子邮件。这是我的控制器中的代码;

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.

我收到一条错误消息,说 require 未定义,我知道这是因为客户端不支持它。我尝试在控制器文件上使用 browserify,然后更新<script>源文件的 index.html 中的标记。这会导致另一个错误。

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?

删除会var pg = require('pg');给出“ReferenceError: pg is not defined”。我只想从我的应用程序连接到 Postgres 数据库并插入一些值。我是在正确的轨道上还是应该以不同的方式处理这个问题?

采纳答案by Dan Kohn

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 Firebaseor IrisCouchso that you don't need to develop the backend at all.

请参阅Can I use PostgreSQL (pg) in the client-side (express/node.js)了解为什么不能让客户端直接连接到您的数据库。您要么想编写(轻量级)服务器应用程序(可能使用 Node.js),要么您应该考虑像FirebaseIrisCouch这样的后端即服务 (BaaS),这样您就不需要在全部。