node 作为当前最受欢迎的"js版"后端开发语言之一,无论是业务开发,还是自动化构建部署,使用是很频繁的。但是…
Node: 最简单的node server
项目结构
主要文件:
- bin/www
- package.json
确定并安装node
$ node -v
bin/www
var http = require('http');
var port = 8000;
/**
* var app = require('../app');
* var server = http.createServer(app);
*/
var data = { key: 'hello', value: 'world'};
var server = http.createServer(function(request,response){
response.writeHead(200,{
'content-type': 'application/json'
});
response.write('Hello World -- 0');
response.end(JSON.stringify(data));
});
server.listen(port);
console.log('Server running on port 8000');
package.json
可以参考配置scripts
{
"name": "node-server",
"version": "1.0.0",
"description": "A project that introduces simple node services",
"main": "N",
"scripts": {
"start": "node ./bin/www",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "lianpf",
"license": "ISC"
}
如果不想增加更多配置, 可以命令行 node ./bin/www 不用配置package.json
启动
$ npm run start //启动server
浏览器直接访问 localhost:8000 , 可以看到response返回数据
拓展
注意看项目结构的同学肯定注意到了没有提到app.js文件, 以及bin/www 文件里注释的app相关的代码, 这里要讲的是app.js是一个配置文件, 可以配置router等相关信息。然后启动node server, 提供接口服务。 这里贴下我之前项目app.js的配置, 有兴趣的同学自己参考拓展
var express = require('express');
var session=require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var connect_more=require('./routes/connect_more');
var find = require('./routes/find');
var hero = require('./routes/hero');
var about_me = require('./routes/about_me');
var app = express();
//app.set设置view engine 为ejs
//app请求index,users
var connect=require('connect');
//app.use设置路由,/分配给routes,/users分配给users
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//app.use设置session回话,单位为毫秒全局变量。
//session 时长为30分钟,这个是以毫秒为单位,这样我们就建立一个session的会话,这是一个全局的设置
app.use(session({ secret: 'joke', key: 'joke_key',cookie: {maxAge: 1800000 }}));
app.use('/', routes);
app.use('/users', users);
app.use('/connect_more',connect_more);
app.use('/find',find);
app.use('/hero',hero);
app.use('/about_me',about_me);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
};
module.exports = app;
注 项目github地址 https://github.com/Wayshower/node-server
最后, 希望大家早日实现:成为编程高手的伟大梦想!
欢迎交流~