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")

相关推荐
不会敲代码116 分钟前
TCP/IP 与前端性能:从数据包到首次渲染的底层逻辑
前端·tcp/ip
kyriewen27 分钟前
奥特曼借GPT-5.5干杯,而你的Copilot正按Token收钱
前端·github·openai
AC赳赳老秦31 分钟前
投标合规提效:用 OpenClaw 实现标书 / 合同自动审核、关键词校验、格式优化,降低废标风险
开发语言·前端·python·eclipse·emacs·deepseek·openclaw
kyriewen38 分钟前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
前端·javascript·设计模式
千寻girling1 小时前
《 Git 详细教程 》
前端·后端·面试
之歆2 小时前
DAY08_CSS浮动与行内块布局实战指南(下)
前端·css
yqcoder3 小时前
CSS Position 全解析:5 种定位模式详解
前端·css
Rhi6373 小时前
从零搭建项目:React 19 + Vite 8 + Tailwind CSS v4 实战配置
前端
竹林8183 小时前
用Viem替代ethers.js:从一次签名失败到完整迁移的实战记录
前端·javascript
之歆3 小时前
DAY08_CSS浮动与行内块布局实战指南(上)
前端·css