2016-08-08 3 views
0

Heroku에서 데이터베이스를 설정했고 2 레코드가있는 users라는 테이블을 만들었습니다. 이제 Express를 통해 Node 어플리케이션에 데이터를 가져 오려고합니다.Express를 통해 MySql에서 데이터 가져 오기

var express = require('express'); 
var router = express.Router(); 

/* GET home page. */ 
router.get('/', function(req, res, next) { 
    // res.render('layout', { title: 'Movieseat' }); 

    connection.connect(); 

    connection.query('SELECT * FROM `users` WHERE `first_name` = "Kees"', function (error, results, fields) { 
     // error will be an Error if one occurred during the query 
     // results will contain the results of the query 
     // fields will contain information about the returned results fields (if any) 
     console.log(results); 
    }); 

    connection.end(); 
}); 

module.exports = router; 

이 인덱스에서하십시오 루트가하는 index.js 파일과 폴더

// connect to the heroku database 
var mysql = require('mysql'); 
var connection = mysql.createConnection({ 
    host  : 'us-cdbr-iron-***-**.cleardb.net', 
    user  : 'bfe4***0ede74', 
    password : '6742****', 
    database : 'heroku_****ee0f0e9102' 
}); 

내가 다음과 같습니다

내 app.js 파일에 그렇게 같은 연결을 설정 한 route first_name Kees의 기록을 제공하려고합니다. 내 호스트를 방문 할 때 나는 다음과 같은 오류가 발생합니다 :

connection is not defined

ReferenceError: connection is not defined

은 그래서 connection 내 경로 파일에 대한 언급이없는 것처럼 보이는,하지만 난 내 응용 프로그램을 얻을 연결을 클릭 + Ctrl을 내 WebStorm의 IDE에. js 파일에서 연결을 정의합니다. 그렇다면 경로 파일에서 연결을 어떻게 참조합니까? 내가하는 index.js 경로 파일에 다음 행의 주석을 해제 할 때

또한 :

res.render('layout', { title: 'Movieseat' }); 

나는 오류 얻을 :

Error: Can't set headers after they are sent. What would be the propper way to request data and render a jade template?

답변

1

두 번째 오류 가능성을 어딘가에 당신이 전화하는거야 고해상도 때문에 .send() 또는 res.end() 또는 res.render()를 사용하면 이미 알지 못합니다. 미들웨어 등을 확인하여 그렇게하지 않는지 확인하십시오.

첫 번째 문제는 연결 파일에서 연결 개체를 내보내거나 라우터 파일에서 연결 개체를 필요로하지 않기 때문입니다. 모듈을 참조하려면 모듈을 명시 적으로 요구해야합니다.

// connect to the heroku database 
var mysql = require('mysql'); 
var connection = mysql.createConnection({ 
    host  : 'us-cdbr-iron-***-**.cleardb.net', 
    user  : 'bfe4***0ede74', 
    password : '6742****', 
    database : 'heroku_****ee0f0e9102' 
}); 
module.exports = connection; 

그런 경우에는 항상 동일한 연결이 있으므로 확장성에 좋지 않습니다. 연결 풀링을 살펴보고 전역 개체를 전달하는 대신 연결을 가져 오는 메서드를 내보내는 것을 고려하십시오. MySQL의 연결을 분리 한 후 재사용하지 않습니다, 당신은 새로 만들 (또는 경로 처리기에 가까운/연결하지 마십시오 - 첫 번째 요청 후 작동하지 않습니다

var express = require('express'); 
var router = express.Router(); 
var connection = require('./path/to/your/connection.js'); 

/* GET home page. */ 
router.get('/', function(req, res, next) { 
    // res.render('layout', { title: 'Movieseat' }); 

    connection.connect(); 

    connection.query('SELECT * FROM `users` WHERE `first_name` = "Kees"', function (error, results, fields) { 
     // error will be an Error if one occurred during the query 
     // results will contain the results of the query 
     // fields will contain information about the returned results fields (if any) 
     console.log(results); 
    }); 

    connection.end(); 
}); 

module.exports = router; 
+1

가 : 라우터에서 다음

, 또는 연결 대신 연결 풀 사용 - 마지막 옵션 선호) –

+0

동의합니다. 나는 텍스트에서 많은 것을 말했지만, 그가 물었던 것을 해결함으로써 개념적으로 그를 시작하려했습니다. – Paul

관련 문제