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

相关推荐
恋猫de小郭5 小时前
AGENTS.md 真的对 AI Coding 有用吗?或许在此之前你没用对?
前端·人工智能·ai编程
sunny_6 小时前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
前端·rust·前端工程化
rfidunion7 小时前
springboot+VUE+部署(12。Nginx和前端配置遇到的问题)
前端·vue.js·spring boot
珹洺8 小时前
Java-servlet(五)手把手教你利用Servlet配置HTML请求与相应
java·运维·服务器·前端·servlet·html·maven
QQ24391978 小时前
语言在线考试与学习交流网页平台信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·spring boot·sql·学习·java-ee
范特西.i8 小时前
QT聊天项目(6)
前端
a1117768 小时前
水体渲染系统(html开源)
前端·开源·threejs·水体渲染
程序员小李白9 小时前
CSS 盒子模型
前端·css·html
Zzz不能停9 小时前
单行 / 多行文本显示省略号(CSS 实现)
前端·css
xiaoxue..9 小时前
TailwindCSS:从“样式民工”到“UI乐高大师”的逆袭
前端·css·ui