Node.js-Hello World HTTP 서버 예제

이 예에서는 Node.js를 사용하여 HTTP 서버를 만드는 방법을 보여줍니다. 서버는 포트 1337에서 수신 대기하고 Hello, World!를 보냅니다. GET 요청시 브라우저에.

포트 1337을 사용하는 대신 현재 다른 서비스에서 사용하지 않는 포트 번호를 선택할 수 있습니다.

http 모듈은 Node.js입니다. 핵심 모듈 (추가 리소스를 설치할 필요가없는 Node.js 소스에 포함 된 모듈)


http 모듈은 http.createServer()를 사용하여 HTTP 서버를 생성하는 기능을 제공합니다. 방법.

응용 프로그램을 만들려면 다음 JavaScript 코드가 포함 된 파일을 만듭니다.


const http = require('http'); // Loads the http module http.createServer((request, response) => {

// 1. Tell the browser everything is OK (Status code 200), and the data is in plain text
response.writeHead(200, {
'Content-Type': 'text/plain'
});
// 2. Write the announced text to the body of the page
response.write('Hello, World! ');
// 3. Tell the server that all of the response headers and body have been sent
response.end(); }).listen(1337); // 4. Tells the server what port to be on

임의의 파일 이름으로 파일을 저장하십시오. 이 경우 이름을 hello.js 파일이있는 디렉토리로 이동하여 다음 명령을 사용하여 애플리케이션을 실행할 수 있습니다.

node hello.js

생성 된 서버는 URL http://localhost:1337로 액세스 할 수 있습니다. 또는 http://127.0.0.1:1337 브라우저에서.

Hello, World!와 함께 간단한 웹 페이지가 나타납니다. 아래 스크린 샷과 같이 상단의 텍스트 :

Node.js 서버 예