利用node搭建简易服务器

//定义数据类型,告诉浏览器如何解码
Response.setHeader('Content-Type','text/html; charset=utf-8')   

搭建简易服务器


const path = require('path')
// 1.引入模块
const http = require('http')

let url = 'D:/学习/node+vue+mysql学习过程/node'   dist放入哪个文件夹,就写哪个文件夹的地址
//引入请求文件模块,file
let file = require('./common/file')

// 2.创建服务器实例
let server = http.createServer()
// 3.服务器要做的事情
server.on('request',(Request,Response)=>{
    let type = path.extname(Request.url)   //识别请求的文件类型,
    let contentType = 'text/html; charset=utf-8' 加载html时会请求css,js,img,png等文件,就需要设置对应的解析类型,html在meta有设置对应的解析类型,所以html类型不用加
    
    let pathUrl = `${url}/dist/index.html` //配置默认地址
    if(Request.url !== '/') {
        pathUrl = `${url}/dist${Request.url}`
    }
    if( type === '.jpg' || type === '.png') {
        contentType = 'image/jpeg'
    }else if (type === '.js') {
        contentType = 'application/x-javascript'
    }else if (type === '.css') {
        contentType = 'text/css'
    }
    Response.setHeader('Content-Type',contentType)
    file.data.getQueryFile(pathUrl,Request,Response)
})
// 4.绑定端口号,自动启动服务器
server.listen(3000,()=>{
    console.log('服务器启动成功,可以通过http://127.0.0.1:3000/  来进行访问')
})

创建请求文件模块file

const fs = require('fs')
function getQueryFile(url,Request,Response) {
    fs.readFile(url,function(error,data){
        if(error) {
            console.log('读取文件失败')
            console.log(error)
            Response.setHeader('Content-Type','text/html; charset=utf-8')
            return Response.end('请求路径错误')
        }else {
            console.log('读取文件成功')
            Response.end(data.toString())
        }
    })
}

let data = {
    getQueryFile,
}
exports.data = data


把打包好的文件放入指定文件区域
在这里插入图片描述
在这里插入图片描述

或者使用express

npm init -y //搭建package.json
然后
npm i express -S

接下来


var express = require('express')
var app = express()

// 找public下的静态资源 访问的话要http://localhost:3000/public/自动找index,如果有指定的就去指定的
// app.use('/public/',express.static('./public/'))
// 进化
// 可以省略掉/public/    http://localhost:3000/自动找这个下面的index
app.use(express.static('public'))

app.use(express.static('static'))

app.get('/',(rep,res) => {
  res.send('我是get请求')
})

app.post('/a',(rep,res)=>{
  res.send('我是post请求')
})

app.listen(3000,()=>{
  console.log('http://localhost:3000/    启动了')
}) 

使用nodemon 可以对项目重新启动

npm i nodemon -g
nodemon xxx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值