res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
code: 0,
msg: '',
result: {
username: 'shasharoman'
}
}));
return;
}
// 没有匹配其他分支的话,执行以下逻辑
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Not Found');
});
// server开始监听,等待请求到来
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
文件内容编辑保存后,在my-server目录下通过命令node index.js启动服务,然后在浏览器中访问http://127.0.0.1:300/、http://127.0.0.1:300/api/user、http://127.0.0.1:300/xxx观察不同结果。
这是官方Guides经过小小修改得到的代码,添加部分注释以及额外逻辑。主要为了更清晰传达以下几个知识点:
从req对象上获取method与url,这个req对象是客户端请求的“抽象表现”,平时写Ajax指定的绝大部分内容都可以从该对象上获取
中间添加的两个if分支,主要是为了让大家了解服务器如何区分不同请求,决定做不同事情,即路由概念
Content-Type: application/json,通常API会使用的响应格式,表明返回数据是json格式,这是一个HTTP头部,属于HTTP协议相关知识
statusCode:404,HTTP最常见的错误“Not Found”,也属于HTTP协议相关知识
往前优化一步
通过上面的代码,实现了一个简单Server,但真实场景下我们会这样去实现吗?答案是肯定不会,所以我们还需要一步步完善,做以下几个修改:
增加config,在其中配置hostname,port
增加controller,用于分层以及分模块
增加route,用于定义路由
代码不多,一共五个文件:
config.js,配置文件
route.js,路由定义文件
controller/account.js,账号模块业务实现文件
controller/index.js,业务汇总并暴露给外部
index.js,项目启动文件
// config.js
exports = module.exports = {
hostname: '127.0.0.1',
port: '3000'
};
// route.js
exports = module.exports = [{
method: 'GET',
path: '/api/user',
impl: 'account.userById'
}, {
method: 'POST',
path: '/api/user',
impl: 'account.createUser'
}];
// controller/account.js
exports.userById = userById;
exports.createUser = createUser;
function userById(req, res) {
res.end('waiting for impl.');
}
function createUser(req, res) {
res.end('waiting for impl.');
}
// controller/index.js









