search

Home  >  Q&A  >  body text

node.js - 页面传给nodejs一个data信息,nodejs连接数据库后把结果返回给页面,不用nodejs其他框架整个流程怎么写?

在页面点击一个按钮,发起get请求,js文件怎么监听到有这个请求然后根据参数查询数据库,和怎么返回给页面。我要整个完整能运行的代码,即连服务器也开启了。因为是新手,所以网上片段式的解答暂时还不能解答我的疑惑。
小女子谢谢各位老大了,我的数据库课设靠你们了

大家讲道理大家讲道理2873 days ago391

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 15:39:07

    It is recommended to use frameworks such as express, because it is quite troublesome to do routing matching yourself. If you go through the express documentation first, I believe you will have a general idea.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 15:39:07

    The function of the framework is mostly to provide a simple routing interface and to remove cumbersome request preprocessing operations.

    const http=require('http');
    //<TODO>数据库连接
    http.createServer((req,res)=>{
        //处理url
        const path = req.url.replace(/\/?(?:\?.*)?$/,'').toLowerCase();
        switch(path){
            case '': todo(req,'/index.html');
            case '/about': todo(req,'/about.html');
            default : todo(req,'/404')
        };
    });
    function todo(res,path){
        //<TODO>数据库操作
    };

    Using express is quite simple, just write the route and corresponding handler:

    const app = require('express')();
    app.listen(3000,(err)=>{
        err && console.log(err);
    });
    app.get('/',handler.home);
    app.get('/about',handler.about);
    app.use((req,res)=>{
        res.status(404);
        res.send('404');
    })

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 15:39:07

    You can teach, but I don’t teach transvestites, haha.

    Go to the Express official website and read the documentation. First understand the routing, and then ask how to connect to the database.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:39:07

    I just used native nodejs to write a blog backend

    reply
    0
  • Cancelreply