nodeLearn(文件夹) begining(文件夹) sever.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
打开[begining]文件夹
$ cd nodeLearn/begining
运行 node.js
$ node server.js
可以看到命令行有日志打印出来了,如下
Server running at http://127.0.0.1:3000/
在浏览器输入
127.0.0.1:3000
,刷新页面 页面有sever.js
打印的hello word
一个简单的有请求
也有返回
的五脏俱全的web服务器搭建成功
/*
* 加载【http】模块,该模块由javascript来编写
* 职责是创建 web 服务器 及 处理http相关的任务等
*/
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
// 通过 createServer 创建 web服务器
const server = http.createServer((req, res) => {
//req 请求体:获取请求相关的信息(请求来自哪里、是get还是post)
//res 响应体:告诉服务器给请求响应什么内容
// 设置响应的请求头状态码是200
res.statusCode = 200;
// 设置返回的文本类型:纯文本
res.setHeader('Content-Type', 'text/plain');
// 最后给客户端返回 hello world
res.end('Hello World!\n');
});
// 通过 listen 监听端口 的请求
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
打开控制台,切换到 console 的窗口,可以执行js逻辑,回车可得到结果
var a=1;var b=2; function add(a,b){return a+b;} add(a,b);
退出sever.js程序运行
Ctrl+C
进入node环境node
输入js逻辑,回车可得到结果 var a=1;var b=2; function add(a,b){return a+b;} add(a,b);
window
,会出现window 的挂载属性等等;命令行输入window
会报错
node
环境里输入process
,会出现process的挂载属性等等;浏览器输入process
会报错( [process]:nodeJs的一个模块,在此不做详细了解)本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。