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