1.get请求时一定要使用get方法进行监听,并且获取传递过来的参数是要使用query,使用post请求时一定要使用post方法进行监听,同时获取数据是
要使用body。
function login() { var name = $('#name').val(); var password = $('#password').val(); if (!name || !password) { alert('用户名和密码都不能为空'); return; } $.ajax( { [javascript] view plain copy type: 'get', url: '/login', data: { name: name, password: password }, dataType: 'json', success: function (data) { if (data) { } }, error: function () { alert('登录失败!'); return; } }); }
后台:
[javascript] view plain copy var express = require('express'); var router = express.Router(); router.get('/login', function (req, res, next) { var name = req.query.name; var pass = req.query.password; console.log('name:' + name); console.log('pass:' + pass); if (name == 'sis' && pass == '1') { res.send('1'); } res.end('is over'); });
post请求:
前台:
[javascript] view plain copy function login() { var name = $('#name').val(); var password = $('#password').val(); if (!name || !password) { alert('用户名和密码都不能为空'); return; } $.ajax( { type: 'post', url: '/login', data: { name: name, password: password }, dataType: 'json', success: function (data) { if (data) { } }, error: function () { alert('登录失败!'); return; } }); }
后台:
[javascript] view plain copy var express = require('express'); var router = express.Router(); router.post('/login', function (req, res, next) { var name = req.body.name; var pass = req.body.password; console.log('name:' + name); console.log('pass:' + pass); if (name == 'sis' && pass == '1') { res.send('1'); } res.end('is over'); });