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?
가 : 라우터에서 다음
, 또는 연결 대신 연결 풀 사용 - 마지막 옵션 선호) –
동의합니다. 나는 텍스트에서 많은 것을 말했지만, 그가 물었던 것을 해결함으로써 개념적으로 그를 시작하려했습니다. – Paul