美文网首页
node学习1

node学习1

作者: kevin5979 | 来源:发表于2020-07-20 17:46 被阅读0次

    什么是Nodejs

    Node.js是一个JavaScript运行环境(runtime),它让JavaScript可以开发后端程序,它几乎能实现其他后端语言能实现的所有功能

    为什么要学Nodejs

    1、Node.js用户量大

    2、Node.js是程序员必备技能

    3、Node.js最擅长高并发 --> 10倍

    4、Node.js简单

    5、Node.js可实现的功能多

    环境搭建

    https://www.runoob.com/nodejs/nodejs-install-setup.html

    http创建web服务

    //表示引入http模块
    const http = require('http')
    /**
     * req  获取客户端传过来的信息-->url
     * res  给浏览器响应信息
     */
    http.createServer((req, res) => {
      console.log(req.url)
      // 设置响应头
      // 状态码200 文件类型 html 字符集utf-8
      res.writeHead(200, { 'Content-Type': "text/html;charset='utf-8'" })
      // 解决乱码
      res.write("<head> <meta charset='UTF-8'></head>")
      
      // 表示给我们页面输出一句话
      res.write("你好 nodejs\n")
      res.write("<h2>你好 nodejs</h2>")
      // 表示给我们页面输出一句话并且结束响应
      res.end('Hello World')
    }).listen(8081);  //端口
    
    console.log('Server running at http://127.0.0.1:8081/')
    
    

    URL模块

    url.parse() 解析URL

    url.format(urlObject) //是上面url.parse()操作的逆向操作

    url.resolve(from,to) //添加或者替换地址

    url.parse()

    cmd -> node -> var url = require('url')

    ->url.parse("http://www.baidu.com?a=xxx")

    ->url.parse("http://www.baidu.com?a=xxx",true)

    url模块使用

    
    const url = require('url')
    
    let api = 'http://www.baidu.com?name=zhangsan&age=18'
    
    console.log(url.parse(api,true))        
    let getValue = url.parse(api,true).query
    console.log(getValue)
    
    console.log(`姓名:${getValue.name}--年龄:${getValue.age}`)
    
    • 想获取url传过来的name和age
    
    const http = require('http')
    const url = require('url')
    http.createServer((req, res) => {
      //http://127.0.0.1?name=zhangsan&age=18   想获取url传过来的name和age
      res.writeHead(200, { 'Content-Type': "text/html;charset='utf-8'" })
    
      res.write("<head> <meta charset='UTF-8'></head>")
      console.log(req.url)      //获取浏览器访问的地址
      
      if(req.url !== '/favicon.ico'){
          let userInfo = url.parse(req.url,true).query
          console.log(`姓名:${userInfo.name}--年龄:${userInfo.age}`)
      }
        
      res.end('Hello World')
    }).listen(8081);  
    
    console.log('Server running at http://127.0.0.1:8081/')
    

    Nodejs自启动工具supervisor

    安装supervisor

    npm install -g supervisor
    

    使用supervisor代替node命令启动应用

    supervisor app.js
    
    END

    相关文章

      网友评论

          本文标题:node学习1

          本文链接:https://www.haomeiwen.com/subject/bzmjcktx.html