'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.jshtml
'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>"); }
1.下載babel-registeres6
npm install babel-register -S
2.下載babel-preset-es2015npm
npm install babel-preset-es2015 --save-dev
main.jsjson
require('babel-register'); require('./src/server');
server.jsbabel
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.jsapp
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"); }