创建简单的node服务器实例(分享)
话不多说直接上代码:
varhttp=require('http')
//对URL解析为对象
//1.导入模块URl模块
varurl=require('url') varfs=require('fs') varpath=require('path') varmime=require('./mime.js') varqs=require('querystring') http.createServer(function(req,res){ varurl1=req.url varpathname=url.parse(url1).pathname //打印路径 console.log(pathname) //取扩展名 varext=path.extname(pathname).slice(1) varcontentType=mime.types[ext] fs.exists(__dirname+pathname,function(e){ if(e){ console.log("文件存在") fs.readFile(__dirname+pathname,function(err,data){ if(!err){ //返回数据 res.writeHead(200,{"Content-Type":contentType+";charset=utf-8","Access-Control-Allow-Origin":"*"}) res.write(data) res.end() }else{ console.log("读文件出错") } }) }else{ console.log("文件不存在") } }) //设置端口 }).listen(9796)
好啦!大概就是这个样子!
有不懂得留言问我哦!
以上这篇创建简单的node服务器实例(分享)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。