Node.js创建第一个web服务

如果用PHP来编写后端代码,需要用Apache或者Nginx的服务器,来处理客户的请求响应。对于Node.js时,不仅实现了应用,同时还实现了整个HTTP服务器.

安装 Node Snippets插件(编程自带提示)

console.log('你好nodejs');

javascript 复制代码
//表示引入http模块
var http = require('http');
/*
request 获取url传过来的信息
response 给浏览器响应信息
*/
http.createServer(function (request, response) {
    //设置响应头
  response.writeHead(200, {'Content-Type': 'text/plain'});
  //表示给页面上面输出一句话并且结束响应
  response.end('Hello World!');
}).listen(8081);//端口

console.log('Server running at http://127.0.0.1:8081/');
javascript 复制代码
//引入http模块
const http=require('http');

//http.createServer((req,res)=>{
http.createServer(function (req,res) {

    //req 获取客户端传过来的信息
    //res 给浏览器响应信息
    console.log(req.url);//获取url
    //设置响应头
    //状态码是200,文件类型是html,字符集是utf-8
    res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"});  //解决乱码
    res.write("<head><meta charset='UTF-8'></head>");  //如果没有这一行,下面的 "你好" 是乱码 //解决乱码
   
    res.write('this is nodejs');
    res.write('你好 nodejs');

    res.end();//结束响应,如果没有这一行,浏览器左上角的图标一直在转圈
}).listen(3000);  //端口建议3000以上,防止冲突

总结:

引入http模块
var http=require("http")

相关推荐
万少1 天前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站1 天前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名1 天前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫1 天前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊1 天前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter1 天前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折1 天前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_1 天前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial1 天前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu2 天前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端