Express js – 如何从ajax调用得到响应?
我试图发送表单数据到服务器端使用ajax(发送用户名),并在服务器端执行SQL查询并将结果传回给我的模板(EJS)。
在我的服务器端(ajaxTest.js)
router.post('/', function(req, res){ console.log(req.body); var query = connection.query("select * from account where username='" + req.body.username+ "'",function (err,result) { console.log(query.sql); if (err) { console.error(err); return; } console.error(result); res.send("Result "+JSON.stringify(result)); });
});
在我的模板(ajaxTest.ejs)
$(document).ready(function () { $("#submit").on("submit",function (e) { e.preventDefault(); data = {}; data.username = 'user101'; $.ajax({ type: 'POST', data: JSON.stringify(data), contentType: 'application/json', url: 'http://localhost:3000/ajaxtest', success: function(data) { console.log('success'); console.log(JSON.stringify(data)); } }); })
});
在上面的代码中,结果已成功login到我的控制台,但“成功”和数据不会返回。 有没有原因为什么结果不被发回模板(ajaxTest.ejs)?
我将不胜感激关于情况的任何反馈!
res.send("Result "+JSON.stringify(result));
发送无效的json。
可以使用:
res.send(JSON.stringify(result));
要么
res.json(result);
它的原因是你通过在“结果”前加上了JSON的语法。
res.send("Result "+JSON.stringify(result));
相反,简单
res.send(JSON.stringify(result));
您的前端需要json数据。 你的后台也应该返回相应的数据。
在你的node.js上,请改变返回行
res.send("Result "+JSON.stringify(result));
至
res.status(201).json(result); // return status 201, and json data (do not stringify)