手机版

node.js接口的一种简单实现方法

时间:2021-08-31 来源:互联网 编辑:宝哥软件园 浏览:

最近想写一个工具界面,集成项目的功能属性,方便其他部门的人编辑,有点类似后台。会有一些数据交互。所以我学习了node.js后端的知识。

源代码如下:

//filename:myServer.js//一个简单的http servervar fs=require('fs ')、url=require('url ')、path=require('path ')、http=require(' http ');//从命令行参数获取根目录,默认为当前目录varroot=path . resolve(process . argv[2]| | ' . ');console . log(' Static root dir : ' root);//create server var server=http . create server(函数(request,response){//获取URL var pathname=URL . parse(request . URL)的路径。pathname,//获取对应本地文件的路径filepath=path.join (root,pathname);//获取文件状态fs.stat(文件路径,函数(err,stats) {if(!err stats . IsFile()){ console . log(' 200 ' request . URL);//send response . write head(200);//将文件流定向到responsefs。createreadstream(文件路径)。管道(响应);} else { console . log(' 404 ' request . URL);response . write head(404);response.end('404未找到');} });});server . listen(8081);console.log('服务器运行于http://127 . 0 . 0 . 1:8081/');本项目的目录结构如下:

js和html页面正常写入后执行cnd命令:

最终效果如下:

以上node.js接口的简单实现方法是边肖分享的全部内容,希望能给大家一个参考和支持。

版权声明:node.js接口的一种简单实现方法是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。