2014-01-19 2 views
1

문제없이 node.js에서 다른 프로그램을 실행할 수 있습니다. NODE.js를 통해 MySQL에 연결하려면 터미널에 nodejs mysqlConnection.js을 입력하고 브라우저에 http://localhost:8080/을 입력하면 영원히로드됩니다.MySQL에 연결할 때 Nodejs가 페이지를로드 할 수 없습니까?

내 코드는 다음과 같습니다 :

// Include http module, 
var http = require('http'), 
// And mysql module you've just installed. 
    mysql = require("mysql"); 

// Create the connection. 
// Data is default to new mysql installation and should be changed according to your configuration. 
var connection = mysql.createConnection({ 
    user: "root", 
    password: "", 
    database: "framework" 
}); 

// Create the http server. 
http.createServer(function (request, response) { 
    // Attach listener on end event. 
    request.on('end', function() { 
     // Query the database. 
     connection.query('SELECT * FROM words;', function (error, rows, fields) { 
     response.writeHead(200, { 
      'Content-Type': 'x-application/json' 
     }); 
     // Send data as JSON string. 
     // Rows variable holds the result of the query. 
     response.end(JSON.stringify(rows)); 
     }); 
    }); 
// Listen on the 8080 port. 
}).listen(8080); 

주의 : 나는 문제없이 PHP를 통해 내 데이터베이스에 연결하기 때문에 MySQL의 연결이 올바른지.

NB : 내 안에는 내 js 파일 옆에 node_modules이라는 폴더가 있는데, 그 안에 mysql 폴더가 있습니다.

나는 NPM을 통해 nodejs를 설치하려고 :

enter image description here

답변

2

request는 응답이을 보낸 경우에만 종료됩니다.

당신은 (즉, 응답이 교착 상태 상황이 일종의의 결과로, end 핸들러 내에서 전송되기 때문에) 지금까지 응답을 보내지 않고 end 이벤트를 기다리고 있습니다.

@vkurchatkin이 주석에서 지적한 것처럼 요청 스트림이 소비되면 end 처리기는 응답 상태와 관계없이 완전히 소비 된 후에 호출됩니다. 이 경우 요청은 전혀 소비되지 않았으므로 응답을 보낸 후에 end 처리기가 (요청 티 아웃의 일부로) 호출되었을 것입니다. 나는 URL에 갈 때

http.createServer(function (request, response) { 
    connection.query(..., function(error, rows, fields) { 
    // TODO: handle `error` 
    response.writeHead(200, { 
     'Content-Type': 'x-application/json' 
    }); 
    response.end(JSON.stringify(rows)); 
    }); 
}); 
+0

그것은 다운로드 창을 엽니 다 :

그래서이 문제를 해결해야 전부 end 핸들러를 제거. 헤더가 인식되지 않는다고 생각합니다. – ALH

+1

'application/json'을 사용해보십시오. JSON 데이터에 적합한 콘텐츠 유형입니다. – robertklep

+0

고맙습니다. 그것은 내 문제를 해결! ;-) – ALH

관련 문제