Create Nodejs project on Ubuntu 18.04

Install NodeJS

~$ sudo apt-get install nodejs

Install npm

~$ sudo apt-get install npm

Create node project

Create project directory

~$ mkdir Desktop/NodeProject

Initialization project

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

Create a directory to put html static page, put js directory src:

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

Put index.html in the static web directory 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>

Write server file 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");
});

Start service

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

Open the browser and you can visit http: // localhost: 8080.
Insert picture description here

Published 381 original articles · praised 85 · 80,000 views +

Guess you like

Origin blog.csdn.net/weixin_40763897/article/details/105140732
Recommended