企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
使用req.body.xxx来获取请求数据(测试中文可用,不乱码): ~~~ var username = req.body.username var pwd = req.body.pwd ~~~ 以用户登录为例: login.html ~~~ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="../javascripts/jquery-3.2.0.min.js" ></script> <script> $(function(){ $("#btn_login").click(function(){ $.ajax({ url:"../users/login", type:"post", data:{username:$("#username").val(),pwd:$("#pwd").val()}, dataType:"json", success:function(data) { if(data.result) { location.href = "main.html"; } else{ alert("登录失败"); } } }); }); }) </script> </head> <body> <input type="text" name="username" id="username" /> <input type="password" name="pwd" id="pwd" /> <button id="btn_login">登录</button> </body> </html> ~~~ user.js ~~~ router.post('/login', function(req, res, next) { var username = req.body.username; var pwd = req.body.pwd; res.send('{"username":"'+username+'","pwd":"'+pwd+'"}'); }); ~~~ 请求路径为rest时,使用以下方式获取: ~~~ router.get('/rest/:id', function(req, res, next) { //获取表单数据 var username = req.params.id; console.log(username); res.send('respond with a resource'); }); ~~~ 响应: 1. 响应字符串: ~~~ res.send('respond with a resource'); ~~~ 2. 响应ajax ~~~ res.send('{"result":true}'); res.json(obj); ~~~ 3. 响应html ~~~ router.get('/helloworld', function(req, res, next) { res.redirect("html/helloworld.html"); }); ~~~ 4. 响应模板页面 ~~~ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); ~~~