a simple web server with node
[intro] simple web server with node-info
if you’ve ever built a static HTML website before, or are coming form a PHP or ASP background, you’re probably used to the idea of the web server (apache or iis) serving your static files so that a browser can view them over the network.
for example, if you create the file about.html , and put it in the proper directory, you can then navigate to `https://localhost/about.html , and put in the proper directory,depending on your web server configuration, you might even be able to omit the. html, but the relationship between url and filename is clear : the web server simply knows where the file is on the computer, and serves it to browser
*localhost, as the name implies, refers to the computer your’re on. This is a common alias for the IPv4 loopback adress::1. you will often see 127.0.0.1 used instead, but i will be using localhost in this. we can keep in mind that browsing to locahost will not connect to that computer*
node offers a different paradigm than that of a traditional web server : the ap that you write is the web server. node simply provides the framework for you to build a web server.
if you way you don’t want to write a web server, it’s a natural response ! you wnat to be writting an app, not a web server. however, node makes the business of writing this web server a simple affair( just a few lines, even ) and the control you gain over your application in return is more than worth it.
Hello world - making simple server
i’ve always found it unfotunate that the canonical introductory programming example is the uninspired message “HELLO WORLD"
even more, in korean, -llo(로) means go toward. that means hello world could be translated as lets go the hell, world!
actually it seems almost sacrilegious at this point to fly in the face of such ponderous tradition, so we’ll start there and move on.
examples
var http = require('http')
http.createServer(function(req.res){
res.writeHead(200, {'content type': 'text/plain'});
}).listen(3000);
console.log('server started on localhost:3000; ...')
💥make sure you are in the same directory as helloworld.js and type node hello wolrd.js
open up a browser and navigate to http//localhost:3000 and , tada!
that’s a new web server. this particular one doesn’t serve HTML; rather, it just transmits the message “hello world” in plaintext to your browser. if you want, you can esperiment with sending HtmL instead : just text/plain to text/ html and change hello world to a string containing valid HTML. I didn’t demonstrate that, because i don’t like to wirte html inside javascript for reasons that will be discussed in more detail in other post
'2023 공부한것들' 카테고리의 다른 글
WIL : 20230614-20230618 (0) | 2023.06.18 |
---|---|
[node.js] es? (es5, es6) (0) | 2023.06.18 |
[node js] npm (0) | 2023.06.18 |
[TIL] 20230618 : what's your name? (0) | 2023.06.18 |
[node.js] console.log function (0) | 2023.06.17 |