前端培训丁鹿学堂:nodejs之http光速入门指南

62 阅读1分钟
createServer创建服务对象

http是网络模块。createServer方法就是创建服务,调用它以后会生成一个服务对象。 服务对象on方法可以监听请求request,在回调里进行响应。 listen方法是监听浏览器请求,第一个参数是端口号,第二个是回调,可以让后端看到服务是否正常。

回调函数的req是携带浏览器参数的,res是返回的数据。

res的write方法是给浏览器传内容,必须要以end方法结尾,否则浏览器不知道响应结束了。end以后的不能再写内容了。

var http = require('http')
// 创建服务器
var serve = http.createServer()
serve.on('request',(req,res)=>{
    res.write('hello nodejs')
    res.end()

})
serve.listen(3000,()=>{
    console.log('ok')
})
node返回网页内容给浏览器

需要在request的回调函数里带上渲染类型为html,页面才能解析。 res.writeHead(200,{"Content-Type":"text/html"}) req的url携带了前端的路由,我们根据不同的路由返回不同的内容,实现一个最简单的web服务器

封装一个模块:功能:根据不同的url返回不同的内容

let renderHtml = (url)=>{
    // 模拟路由
    let content = ''
    switch(url){
        case '/home':
            content = ` <html>
            <h1>home-page<h1>
        </html>`
        break;
        case '/list':
            content = `
            <html>
            <h1>list-page<h1>
        </html>
            `
        break;
        default:
            content = `
            <html>
            <h1>404- not found<h1>
        </html>
            `
    }
    return content
}
module.exports = {
    renderHtml 
}

引入使用模块,注意,引入的模块是一个对象,用点方法调用函数

var http = require('http')
var renderHtmlModule = require('./module/renderHtml.js')
// 创建服务器
var serve = http.createServer()
serve.on('request',(req,res)=>{
    console.log(req.url) // /api/zzz
    if(req.url === '/favicon.ico'){
        return false
    }
    res.writeHead(200,{"Content-Type":"text/html"})
    res.write(renderHtmlModule.renderHtml(req.url))
    res.end()

})
serve.listen(3000,()=>{
    console.log('ok')
})

以上就是node 的http模块的简单介绍,实际开发中我们会使用第三方框架,但是作为基础,最基本的概念还是要掌握的。