0
点赞
收藏
分享

微信扫一扫

Ubuntu18.04创建Nodejs工程


安装NodeJS

~$ sudo apt-get install nodejs

安装npm

~$ sudo apt-get install npm

创建node工程

创建工程目录

~$ mkdir Desktop/NodeProject

初始化工程

~/Desktop/NodeProject$ npm init -y
~/Desktop/NodeProject$ npm i --save express
~/Desktop/NodeProject$ tree -L 1
.
├── node_modules
├── package.json

创建一个目录放html静态页面,放js目录src:

~/Desktop/NodeProject$ mkdir html
~/Desktop/NodeProject$ mkdir src

在静态网页目录html放index.html:

<html>
<head>
<meta charset="utf-8"/>
<title></title>
<style>
div{
width:100px;
height:100px;
background:pink;
}
</style>
</head>
<body>
<h1>This is a box</h1>
<form action="http://localhost:8080/login" method="POST">
账号<input type="text" name="name"/><br>
密码<input type="password" name="password"/><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>

编写服务器文件server.js

// 引入express框架
var express=require("express");
var app=express();
// 指定静态网页目录,并监听8080端口
app.use(express.static("html")).listen(8080);
// 引入body-parser
app.use(require('body-parser')());
// /login接口
app.post('/login',function(req,res){

if(req.body.name == 'tom' && req.body.password == '123'){
res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'});
res.end("登录成功");
}else{
res.writeHead(400,{'Content-Type':'text/plain;charset=utf-8'});
res.end("登录失败");
}
console.log(req.body.name);
console.log(req.body.password);
});
// /hello接口
app.get('/hello',(req,res)=>{

res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'});
res.end("Hello world");
});

启动服务

~/Desktop/NodeProject$ node src/server.js

打开浏览器可以http://localhost:8080就可以访问了。

Ubuntu18.04创建Nodejs工程_html


举报

相关推荐

0 条评论