Node.js与前端开发实战|青训营笔记

59 阅读1分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 十四 天

image.png

image.png cdn 负载均衡

  1. CSR, SSR, SSG
  2. 什么是 Next.js
  3. Next.js 客户端开发
  4. Next.js 服务端开发
  5. 项目核心功能讲解
var http = require('http');
var fs = require('fs');
var url = require('url'); 
// 创建服务器 http.createServer( function (request, response) 
{ // 解析请求,包括文件名 
var pathname = url.parse(request.url).pathname; 
// 输出请求的文件名 
console.log("Request for " + pathname + " received.");
// 从文件系统中读取请求的文件内容 fs.readFile(pathname.substr(1), function (err, data) { if (err) { console.log(err); 
// HTTP 状态码: 404 : NOT FOUND 
// Content Type: text/html response.writeHead(404, {'Content-Type': 'text/html'}); }
else{ // HTTP 状态码: 200 : OK
// Content Type: text/html 
response.writeHead(200, {'Content-Type': 'text/html'}); 
// 响应文件内容 
response.write(data.toString()); }
// 发送响应数据 
response.end(); 
});
}).listen(8080); 
// 控制台会输出以下信息 
console.log('Server running at http://127.0.0.1:8080/');

执行 server.js 文件:

$ node server.js
Server running at http://127.0.0.1:8080/

Node 创建 Web 客户端需要引入 http 模块,创建 client.js 文件

var http = require('http');
// 用于请求的选项
var options = { host: 'localhost', port: '8080', path: '/index.html' }; 
// 处理响应的回调函数 
var callback = function(response){ 
// 不断更新数据 var body = '';
response.on('data', function(data) { body += data; });
response.on('end', function() { 
// 数据接收完成 console.log(body); }); }
// 向服务端发送请求
var req = http.request(options, callback); req.end();

回调函数是异步执行的,并且有异常堆栈错误追踪。 如果回调函数抛出一个异常,进程会触发一个 'uncaughtException' 异常,如果没有被捕获,进程将会退出。

null 在回调函数中作为一个参数有其特殊的意义,如果回调函数的首个参数为 Promise 拒绝的原因且带有返回值,且值可以转换成布尔值 false,这个值会被封装在 Error 对象里,可以通过属性 reason 获取。