zoukankan      html  css  js  c++  java
  • 使用 NodeJS + Express从GET/POST Request 取值

    过去无论哪一种网站应用程式的开发语言,初学者教学中第一次会提到的起手式,八九不离十就是GET/POST Request 的取值。但是,在Node.js + Express 的世界中,仿佛人人是高手,天生就会使用,从不曾看到有人撰文说明。

    这应该算是开发Web Service 的入门,在Client 与Server 的互动中,浏览器发出GET/POST Request 时会传值给Server-side,常见应用就是网页上以POST method 送出的表单内容,或是网址列上的Query Strings (ex: page?page=3&id=5)。然后,我们的网站应用程式透过解析这些参数,得到使用者上传的资讯。

    取得GET Request 的Query Strings:

    GET /test?name=fred&tel=0926xxx572

    app
    .get('/test',function(req, res){
        console
    .log(req.query.name);
        console
    .log(req.query.tel);
    });

    如果是透过表单且是用POST method:

    <formaction='/test'method='post'> 
       
    <inputtype='text'name='name'value='fred'>
       
    <inputtype='text'name='tel'value='0926xxx572'>
       
    <inputtype='submit'value='Submit'>
    </form>
    app.post('/test',function(req, res){
        console
    .log(req.query.id);
        console
    .log(req.body.name);
        console
    .log(req.body.tel);
    });

    当然也可以Query Strings 和POST method 的表单同时使用:

    <formaction='/test?id=3'method='post'> 
       
    <inputtype='text'name='name'value='fred'>
       
    <inputtype='text'name='tel'value='0926xxx572'>
       
    <inputtype='submit'value='Submit'>
    </form>
    app.post('/test',function(req, res){
        console
    .log(req.query.id);
        console
    .log(req.body.name);
        console
    .log(req.body.tel);
    });

    顺带补充,还有另一种方法传递参数给Server,就是使用路径的方式,可以利用Web Server 的HTTP Routing 来解析,常见于的各种Web Framework。这不算是传统标准规范的做法,是属于HTTP Routing 的延伸应用。

    GET /hello/fred/0926xxx572

    app
    .get('/hello/:name/:tel',function(req, res){
        console
    .log(req.params.name);
        console
    .log(req.params.tel);
    });
     

     

    (责任编辑:CIT.CN)

  • 相关阅读:
    Using X++ code Hided to Main Content Panel Frame
    Call a method on caller form
    Infolog in the Dynamics AX 2009
    Using X++ code Customizations to statusLine
    Using X++ Code force Synchronisation DataBase
    英语口语精选100句(转)
    OpenPrinter_1: rc:0 lastError:1801(0x709) The printer name is invalid
    30岁前不要去在乎的29件事(转)
    安全措施挡出黑客攻击
    接口的实便
  • 原文地址:https://www.cnblogs.com/neights/p/3779451.html
Copyright © 2011-2022 走看看