从Angular和NodeJS应用上的server.js文件连接到数据库

时间:2018-11-12 22:43:31

标签: node.js angular heroku angular6

我的角度项目中有两个文件: server.js db_connection.js 。我在Heroku上托管该项目。

server.js 当前正在运行,因为在我的package.json中,我有"start": "node server.js"

我也想连接到数据库,但是我想把它放在一个单独的文件中,叫做 db_connection.js 。我应该如何确保该文件中的代码运行?我可以从 server.js 调用它吗?如果可以,怎么办?

我的文件:

server.js:

const express = require('express');
const app = express();
const path = require('path');

app.use(express.static(__dirname + '/dist/my-app'));

app.listen(process.env.PORT || 8080);

// PathLocationStrategy
app.get('*', function (req, res) {
    res.sendFile('dist/my-app/index.html' , { root : __dirname});
  });

console.log('Console Listening')

db_connection.js:

var mysql = require('mysql');

var con = mysql.createConnection({
    host: "my_server.net",
    user: "my_username",
    password: "my_password"
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
  });

1 个答案:

答案 0 :(得分:0)

您可以这样做。

server.js

const express = require('express');
const app = express();
const path = require('path');
const db = require('./db_connection')

app.use(express.static(__dirname + '/dist/my-app'));

app.listen(process.env.PORT || 8080);

// PathLocationStrategy
app.get('*', function (req, res) {
    res.sendFile('dist/my-app/index.html' , { root : __dirname});
});

app.get('/getSomethingFromDB', db.getSomethingFromDB)

app.post('/postSomethingToDB', db.postSomethingToDB)

console.log('Console Listening')

db_connection.js

const mysql = require('mysql')
const con = mysql.createConnection({
    host: "my_server.net",
    user: "my_username",
    password: "my_password",
    database: 'my_db_name'
});

con.connect( err => {
    if (err) throw err;
    console.log("Connected")
});

module.exports = {

    getSomethingFromDB: (req, res) => {
        const getQuery = `SELECT * FROM some_table WHERE condition`
        con.query(getQuery, (error, results, fields) => {
            if (error) {
                return res.status(500).send("DB Error")
            } else {
                return res.status(200).send(results)
            }
        })
    },

    postSomethingToDB: (req , res) => {
        // Your code for post requests
    },

    // Similarly other functions

}