美文网首页
nodejs-创建Express实例

nodejs-创建Express实例

作者: AdrianRD | 来源:发表于2016-11-14 18:48 被阅读73次

    安装 Express

    打开cmd,进入到项目文件夹的根目录

    npm install express --save

    安装Express

    npm install cookie-parser --save
    npm install multer --save```

    安装模块

    安装完成后,可以看到根目录下自动生成了一个名为node_modules的文件夹,里面含有刚才安装的模块

    node_modules文件夹

    GET方法

    新建index.htm文件

    <html>
    <body>
    <form action="http://127.0.0.1:8081/process_get" method="GET">
    First Name: <input type="text" name="first_name">  <br>
    
    Last Name: <input type="text" name="last_name">
    <input type="submit" value="Submit">
    </form>
    </body>
    </html>
    

    新建server.js文件

    var express = require('express');
    var app = express();
    
    // app.use(express.static('public'));
    
    app.get('/index.htm', function (req, res) {
       res.sendFile( __dirname + "/" + "index.htm" );
    })
    
    app.get('/process_get', function (req, res) {
    
       // 输出 JSON 格式
       response = {
           first_name:req.query.first_name,
           last_name:req.query.last_name
       };
       console.log(response);
       res.end(JSON.stringify(response));
    })
    
    var server = app.listen(8081, function () {
    
      var host = server.address().address
      var port = server.address().port
    
      console.log("应用实例,访问地址为 http://%s:%s", host, port)
    
    })
    

    执行代码

    node server.js

    浏览器访问 http://127.0.0.1:8081/index.htm

    get方法

    POST 方法

    修改index.htm文件为

    <html>
    <body>
    <form action="http://127.0.0.1:8081/process_post" method="POST">
    First Name: <input type="text" name="first_name">  <br>
    
    Last Name: <input type="text" name="last_name">
    <input type="submit" value="Submit">
    </form>
    </body>
    </html>
    

    修改server.js文件为

    var express = require('express');
    var app = express();
    var bodyParser = require('body-parser');
    
    // 创建 application/x-www-form-urlencoded 编码解析
    var urlencodedParser = bodyParser.urlencoded({ extended: false })
    
    app.use(express.static('public'));
    
    app.get('/index.htm', function (req, res) {
       res.sendFile( __dirname + "/" + "index.htm" );
    })
    
    app.post('/process_post', urlencodedParser, function (req, res) {
    
       // 输出 JSON 格式
       response = {
           first_name:req.body.first_name,
           last_name:req.body.last_name
       };
       console.log(response);
       res.end(JSON.stringify(response));
    })
    
    var server = app.listen(8081, function () {
    
      var host = server.address().address
      var port = server.address().port
    
      console.log("应用实例,访问地址为 http://%s:%s", host, port)
    
    })
    

    再用浏览器访问试试

    相关文章

      网友评论

          本文标题:nodejs-创建Express实例

          本文链接:https://www.haomeiwen.com/subject/suzhpttx.html