Node.js学习4~搭建web服务的2种常见方式,附上代码和运行效果

x33g5p2x  于2021-12-15 转载在 其他  
字(0.7k)|赞(0)|评价(0)|浏览(225)

1.使用http搭建web服务

var http = require('http');
http.createServer(function (request, response) {
 response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
response.write('Hello World');
 response.end();//不写则没有http协议尾
}).listen(8080);
console.log('Server running at http://localhost:8080/');

运行结果如下:

2.使用express搭建web服务

express需要提前安装一下,安装命令如下:

代码如下:

//引用express
var express = require("express");
//express定义为app
var app = express();
//app的get传输方法,当网站为localhost: 8080/页面相应 express Hello World!!!!!
app.get("/",function(req,res){
    res.send("express Hello World");
});
//设置端口为8080,加载web服务器启动
app.listen(8080,function(){
    console.log("Server running at http://localhost:8080/")
})

运行结果如下:

相关文章

微信公众号

最新文章

更多