创建server.js
'use strict';
//http模块
var http = require('http');
//封装的方法
var handlers = require('./handlers');
//创建服务
var server = http.createServer(function(request, response) {
//url地址
var url = request.url;
if(url === '/'){
handlers.homepage(request, response);
}else if (url === "/profile") {
handlers.profile(request, response);
} else {
handlers.notFound(request, response);
}
});
//端口3000
server.listen(3000);
console.log('start 3000');
handlers.js
'use strict';
//首页
exports.homepage = function(request, response){
response.setHeader('Content-Type', 'text/html');
response.end('<h1>helloworld</h1>')
}
//一个接口
exports.profile = function(request, response){
var profile = {
name : 'will',
age : 35
}
response.setHeader('Content-Type','application/json');
response.end(JSON.stringify(profile));
}
//404
exports.notFound = function(request, response) {
response.statusCode = 404;
response.setHeader("Content-Type", "text/html");
response.end("<h1>404 Not Found!</h1>");
}
es6写法
1.下载babel-register
npm install babel-register -S
2.下载babel-preset-es2015
npm install babel-preset-es2015 --save-dev
main.js
require('babel-register');
require('./src/server');
server.js
import http from 'http';
import { homepage, notFound } from './handlers';
const server = http.createServer((request, response) =>{
homepage(request, response);
});
server.listen(3000);
console.log('listen 3000');
handlers.js
export function homepage(request, response){
response.setHeader("Content-Type", "text/html");
response.end("hello world");
}
export function notFound(request, response){
response.setHeader("Content-Type", "text/html");
response.end("404");
}