zoukankan      html  css  js  c++  java
  • node.js入门(一)搭建一个简单的服务

    1、先在项目下新建一个server.js,任何浏览器和服务器的通讯都是通过http来完成的,所以先引入http模块(这是一个系统模块)

    const http = require('http')
    

    2、既然引入了那就要使用它,通过他的createServer()方法创建服务;创建服务之后还要添加监听的端口,这样才知道你找的是谁,监听端口使用listen()方法

    const http = require("http")
    
    var server = http.createServer(function (req,res) {
        console.log("你来了")
    })
    
    server.listen(8080)

    这时在小黑窗运行服务node server.js,然后在浏览器访问localhost:8080,可以看到小黑窗输出了“你来了”,但是浏览器一直在转圈圈,那是因为服务器没有向浏览器返回任何内容

    3、想要浏览器显示内容也很简单,createServer()回调函数有两个参数,分别是request和response,request是前端请求的数据,而response就是服务器向浏览器返回的内容

    对上面的代码做一点点修改

    const http = require("http")
    var server = http.createServer(function (req,res) {
        res.write('返回前端的数据');
        res.end();
    })
    server.listen(8080)

    res.write();向前端输出内容、写内容

    res.end();结束

    此时在小黑窗重启服务,然后再浏览器访问localhost:8080,可以在浏览器看到显示了“返回前端的数据”的乱码内容,添加 res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});

    至此,一个简单的服务已经完成

    4、但是这时我们访问任何路径都是返回“返回前端的数据”,正确的应该是根据浏览器的请求来返回内容,这时request参数派上用场了

    打印req可以看到一坨东西,我们只用url就行了,拿到url就可以根据地址来返回数据了

    const http = require("http")
    var server = http.createServer(function (req, res) {
        switch (req.url) {
            case '/news.html':
                res.write("news");
                break;
            case '/article.html':
                res.write("article");
                break;
            default:
                res.write("404");
                break
        }
        res.end()
    })
    server.listen(8080)
    

    重启服务可以看到浏览器访问localhost:8080、localhost:8080/news.html、localhost:8080/article.html,浏览器输出的内容不同了

    至此一个简单服务已经完成了

  • 相关阅读:
    写在学期将要结尾处
    程序有感
    Python字典操作小汇总
    mysql 乱码解决方案
    公告 百度安家
    本周工作安排
    bind1st/bind2nd
    OpenGL放大缩小实现
    Eclipse安装SVN插件
    QQ也玩命令行
  • 原文地址:https://www.cnblogs.com/YAN-HUA/p/10812098.html
Copyright © 2011-2022 走看看