Ubuntu 18.04でNodejsプロジェクトを作成する

NodeJSをインストールする

~$ sudo apt-get install nodejs

npmをインストールする

~$ sudo apt-get install npm

ノードプロジェクトを作成する

プロジェクトディレクトリを作成する

~$ 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

index.htmlを静的Webディレクトリ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にアクセスできます。
ここに画像の説明を挿入

381の元の記事を公開 85を賞賛 80,000ビュー+

おすすめ

転載: blog.csdn.net/weixin_40763897/article/details/105140732