zoukankan      html  css  js  c++  java
  • node必学的Hello World实现--服务器实现

     node是JavaScript运行在后端的一种实现。而后端语言,不管是php,java都需要一个服务器才能跑起来,node如是。

    node的服务器较php而言,少了单独安装服务器的步骤,node的服务器只是几行代码。从这点来说,node简介不少。

    一,原生node实现服务器功能

     1 const http = require('http');
     2 
     3 const hostname = '127.0.0.1';
     4 const port = 3000;
     5 
     6 const server = http.createServer((req, res) => {
     7   res.statusCode = 200;
     8   res.setHeader('Content-Type', 'text/plain');
     9   res.end('Hello World!
    ');
    10 });
    11 
    12 server.listen(port, hostname, () => {
    13   console.log(`服务器运行在 http://${hostname}:${port}/`);
    14 });

    或者可以这样

     1 const http = require('http');
     2 
     3 const hostname = '127.0.0.1';
     4 const port = 3000;
     5 
     6 http.createServer((req, res) => {
     7 
     8   res.end('Hello World!
    ');
     9 }).listen(port, hostname, () => {
    10   console.log(`服务器运行在 http://${hostname}:${port}/`);
    11 });;

    二,使用express框架搭建

     1 const app = require("express")();
     2 
     3 app.get("/",function(req,res){
     4 
     5   res.send('Hello World! dd
    ');
     6 })
     7 //需要专门指定端口号
     8 var server = app.listen(3000, function () {
     9   var host = server.address().address;
    10   var port = server.address().port;
    11   console.log('Example app listening at http://%s:%s', host, port);
    12 });

    简单总结一下,服务器必须要处理好访问路径以及访问端口。

    服务器是跑通前后端的基础。

    本文结束。

  • 相关阅读:
    autocomplete
    ORM组件 ELinq (一)首航之旅
    ORM组件 ELinq 系列
    Jet 驱动对CRUD的支持
    ORM组件 ELinq 更新日志
    年度开源力作ORM组件 ELinq诞生了
    Excel 连接字符串详解
    国内开源ORM组件 ELinq正式版发布
    Firebird 问题总结
    ORM组件 ELinq (二) 映射配置之Table
  • 原文地址:https://www.cnblogs.com/zhensg123/p/9223012.html
Copyright © 2011-2022 走看看