zoukankan      html  css  js  c++  java
  • express使用

    1、安装express命令

    cnpm install express --save

    2、使用方法

    var express = require('express');

    var app = express(); app.get('/', function (req, res) {res.send('Hello World');}) var server = app.listen(8081)

    3、内置的中间件 express.static 

    使用 express.static 中间件来设置静态文件路径。app.use(express.static('public'));

    4、get请求:req.query获取发送的数据

    //index.html文件
    <!DOCTYPE html>
    <html>
    <body>
      <form action="http://localhost:8081/getmethod" 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.html',function(req,res){
        res.sendFile(__dirname + '/'+'index.html')
    })
    app.get('/getmethod',function(req,res){
        var data = req.query;
        console.log(req.query)
        res.send(req.query);
    })
    app.listen(8081)

    执行:node server

    浏览器访问:http://localhost:8081/index.html
    5、post请求:req.body获取发送的数据
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
        </head>
        <body>
            <form action="http://localhost:8082/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();
    app.listen('8082')
    app.use(express.json())
    app.use(express.urlencoded({extended:true}))
    app.use('/post.html',function(req,res){
        res.sendFile(__dirname + '/'+'post.html')
    })
    app.use('/process_post',function(req,res){
        var data = req.body;
        console.log(data);
        res.send(data)
    })

    执行:node server

    浏览器访问:http://localhost:8082/index.html
    6、express.router()
  • 相关阅读:
    Iterable,Iterator和forEach
    集合的线程安全性
    Servlet生命周期
    JavaWeb应用的生命周期
    将博客搬至CSDN
    (五)新类库的构件
    Python input和print函数
    python----调试
    Excel决定吃什么
    MATLAB—地图
  • 原文地址:https://www.cnblogs.com/bing0709/p/10384370.html
Copyright © 2011-2022 走看看