Problem với jquery ajax call post method tới expressjs ???????
-
Em có viết đoạn code trên expressjs như sau:
app.post('/forgot_password', function (req, res) { selectSQL(req,function(temp){ console.log(temp); if(temp === req) { var objUser = { email: req, password: tempPassword }; updateSQL(objUser, function(affected){ if(affected === 1) { mailOptions = { from: 'Nguyễn Duy Đức <[email protected]>', // sender address to: '[email protected]', // list of receivers subject: 'Password changed', // Subject line text: 'Hello, ' + temp + ' your password is: ' + tempPassword, // plaintext body html: '<b style="color: red;">Your password is changed!</b>' // html body }; // send mail with defined transport object transporter.sendMail(mailOptions, function(error, info){ if(error){ return console.log(error); } console.log('Message sent: ' + info.response); }); res.send('Successfully'); } }); } else { res.send("Your email doesn't exits"); } }); });
Và phía client như sau:
<script type="text/javascript"> $('#changePassword').submit(function(event){ event.preventDefault(); var getEmail = document.getElementById('_email').value; $.ajax({ type: 'POST', contentType: 'application/json', type: 'json', url: 'http://localhost:3000/forgot_password', data: JSON.stringify({ email : getEmail }), success: function(msg) { $('#lblResponse').html(msg); }, error: function(xhr, status, error) { $('#lblResponse').html('Error connecting to the server.'); } }); }); </script>
Tình hình là dù có làm thế nào đi nữa thì thằng req.body luôn là undefined thế mới nhọ ạ ??? Bác nào đã có kinh nghiệm thì share em với :3 Em cảm ơn ạ !
-
Bạn dùng markdown để chèn code vào nhé.
Nếu req.body bằng undefined thì bạn kiểm tra xem đã sử dụng middleware body-parser[1] chưa nhé?
-
@fsociety-vn đã nói:
Do mình thử rồi nhưng vẫn lỗi ko add code theo markdown vào đc, add vào đc có phần code kia hiển thị đc thôi :3.
-
ajax lạ nhỉ bt thì mình làm thế này, ko cần phải stringify đâu o.0
$.ajax({ url: '/forgot_password', type: 'POST', data: { email: document.getElementById('_email').value } }).done(function (result) { //bla bla });
cấu hình thằng body-parser cơ bản
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));