简体   繁体   English

通过MySQL Express JS REST API

[英]Express JS REST API with MySQL

I am doing an exercise with Express.js and MySQL. 我正在使用Express.js和MySQL进行练习。 At the moment I have 4 files. 目前,我有4个文件。 The error is, 错误是

TypeError: areas.getAreas is not a function
    at Object.<anonymous> (/--/--/--/src/routes/userRoutes.js:4:13)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/--/--/--/src/app.js:10:20)
    at Module._compile (module.js:653:30)

But I am sure I am declaring the variable and function so, I don't understand why is it happening. 但是我确定我是在声明变量和函数,所以我不明白为什么会这样。

I tried to get the value of the variable areas in the userRoutes.js file but console just show me an "{}". 我试图获取userRoutes.js文件中可变区域的值,但控制台仅向我显示“ {}”。 I also tried to change the sintaxis of the function of the areas.js file, writing it as function and not like an object. 我还尝试更改area.js文件的功能性,将其写为函数而不是对象。

The main file is, app.js and it contains: 主文件是app.js ,它包含:

const express = require('express');
const app = express();
const morgan = require('morgan'); 
const bodyParser = require('body-parser');
const mysql = require('mysql');

const connection = require('/--/--/--/db/connection.js');
const userRoutes = require('/--/--/--/routes/userRoutes.js');

app.set('port', process.env.PORT || 3000);

app.use(morgan('dev'));
app.use(bodyParser.json()); 

connection(mysql);    
userRoutes(app);

app.listen(app.get('port'), ()=> {
    console.log('server on port 3000');
});

The next files are: 接下来的文件是:

connection.js connection.js

'use strict';

module.exports = function connection(mysql){
    mysql.createConnection({
        host: 'http://x.x.x.x',
        user: 'xxxxxxx',
        password: 'xxxxxxx',
        database: 'xxxxxxx'
    })
};

areas.js areas.js

'use strict';

let areasModel = {};
areasModel.getAreas = (callback) => {
    if(connection) {
        connection.query(
            "SELECT * FROM areas",
            (err, rows) => {
                if(err) {
                    throw err;
                }
                else {
                    callback(null, rows);
                }
            }
        );
    }
};

module.exports = areasModel;

userRoutes.js userRoutes.js

'use strict';

const areas = require('../models/areas');

module.exports = function (app) {
    app.get("/", (req,res)=>{
        areas.getAreas((err, data) => {
            res.json([]);
        });
    });
}

尝试在areas.js导入connection.js ,可能是因为从不输入该if语句会返回未定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM