Node.js - ຕົວຢ່າງ Hello World HTTP Server

ໃນຕົວຢ່າງນີ້ພວກເຮົາຈະສະແດງວິທີການສ້າງ HTTP server ໂດຍໃຊ້ Node.js. ເຊີບເວີຈະຟັງຢູ່ທີ່ port 1337, ແລະຈະສົ່ງ Hello, World! ກັບຕົວທ່ອງເວັບຕາມການຮ້ອງຂໍ GET.

ໃຫ້ສັງເກດວ່າ, ແທນທີ່ຈະໃຊ້ພອດ 1337, ທ່ານສາມາດໃຊ້ ໝາຍ ເລກພອດທີ່ທ່ານເລືອກເຊິ່ງປະຈຸບັນບໍ່ໄດ້ໃຊ້ໂດຍບໍລິການອື່ນ.

ໂມດູນ http ແມ່ນ Node.js ໂມດູນຫຼັກ (ໂມດູນລວມຢູ່ໃນແຫຼ່ງຂອງ Node.js, ເຊິ່ງບໍ່ຕ້ອງການຕິດຕັ້ງຊັບພະຍາກອນເພີ່ມເຕີມ).


ການ http ໂມດູນໃຫ້ ໜ້າ ທີ່ໃນການສ້າງ server HTTP ໂດຍໃຊ້ http.createServer() ວິທີການ.

ເພື່ອສ້າງແອັບພລິເຄຊັນ, ສ້າງແຟ້ມເອກະສານທີ່ມີລະຫັດ 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 ໃນ browser.

ໜ້າ ເວບໄຊທ໌ງ່າຍໆຈະປະກົດຂື້ນພ້ອມດ້ວຍ Hello, World! ຂໍ້ຄວາມຢູ່ເທິງສຸດ, ດັ່ງທີ່ສະແດງຢູ່ໃນ ໜ້າ ຈໍຂ້າງລຸ່ມນີ້:

ຕົວຢ່າງ Server Node.js