Node.js 实践基础 | 青训营笔记

66 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 9 天

本文存在两个例子的错误未得到解决!注意复查甄别。

Node.js

第一个node程序

  1. 选择VSCode,编写程序

程序命名 “node_mode.js”,任一级均可

image.png

const http = require('http')

const hostname = '127.0.0.1'
const port = 3000

const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end('Hello World\n')
})

server.listen(port, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})
  1. 打开cmd ,输入 node '对应文件名'
node D:\vscode_project\project_demo\node_demo.js

输出 Server running at http://127.0.0.1:3000/ 即为运行成功

  1. 打开任一浏览器 输入http://127.0.0.1:3000/即可

image.png

获取设置的回复信息

  1. 输入以下代码
const http = require('http')

const port = 3000

const server = http.createServer((req, res) => {
  const bufs = []
  req.on('data',(buf)=>{
    bufs.put(buf)
  })

  req.on('end', () => {
    //bufs
    const buf = Buffer.concat(bufs).toString('utf8')
    let msg = 'hello'
    try{
      const ret = JSON.parse(buf)
      msg = ret.msg

    }catch(err){

    }
    const responseJson = {
      msg:`receive:${msg}`
    }
    res.setHeader('Content-Type','application/json')
    res.end(JSON.stringify(responseJson))
  })
})

server.listen(port, () => {
  console.log(`linstening on:`, port)
})
  1. node 文件名.js
  2. 获得结果

image.png

ps : 注意

msg:`receive:${msg}`

的符号

发送信息(存在未知错误)

  1. 输入代码

文件名:http_client.js

const http = require('http')

const body = JSON.stringify({
    msg:'Hello from My own client',
})

const req = http.request('http://127.0.0.1:3000', {
    method:'POST',
    headers: {
        'Content-Type':'application/json',
    }
}, (res)=>{
    const bufs = []
    res.on('data',(buf)=>{
        bufs.push(buf)
    })
    res.on('end',()=>{
        const buf = Buffer.concat(bufs)
        const json = JSON.parse(buf)

        console.log('json.msg is ', json.msg)
    })
})
req.end(body)

正确连接的结果是 能成功连接 我目前是报错的

网站模拟

  1. 新建包static,在里面创建index.html,如图所示

image.png

  1. index.html代码如下
<!DOCTYPE html>
<html>
    <head>
        <title>My Application</title>
    </head>
    <body>
        <h1>Hello</h1>
        <script>
            alert('yes')
        </script>
    </body>
</html>
  1. 在static的同级文件夹下创建文件static_server.js
  2. 代码如下
const http = require('http')
const fs = require('fs')
const path = require('path')
const url = require('url')

const folderPath = path.resolve(__dirname,'./static')

const server = http.createServer((req,res)=>{
    //expected http://127.0.0.1:3000/index.html?abc=10
    const info = url.parse(req.url)
    
    //static/index.html
    const filepath = path.resolve(folderPath,'./'+info.path)

    console.log('filepath',filepath)

    //stream api
    const filestream = fs.createReadStream(filepath)
    filestream.pipe(res)

    //
})

const port = 3000

server.listen(port,() =>{
    console.log('listening on:',port)
})
  1. 打开终端,运行static_server.js文件
  2. 打开浏览器 输入 http://127.0.0.1:3000/index.html

image.png

image.png

存在导包错误

  1. 创建ssr_example.js文件
const React = require('react')
const ReactDOMServer = require('react-dom/server')
const http = require('http')

function App(props){
    // return <div>Hello</div>
    return React.createElement('div',{}, props.children || 'Hello')
}

const server = http.createServer((req, res) => {
  res.end(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>My Application</title>
        </head>
        <body>
            ${ReactDOMServer.renderToString(
                React.createElement(App, {}, 'my_content'))}
            <script>
                // 在浏览器上初始化应用
            </script>
        </body>
        </html>
    `)
})

const port = 3000

server.listen(port, () => {
  console.log(`listening on:`,port)
})

其中将模板字符串替代模板引擎 2. node 目标文件 3. 打开浏览器 输入 http://127.0.0.1:3000/index.html