我有这样的功能:
exports.saveAction = function (req,res) { var conn = MysqL.createConnection({ host : nconf.get("database:host"),//port: 3306,user : nconf.get("database:username"),password : nconf.get("database:password"),database : nconf.get("database:database"),multipleStatements: true,//ssl: 'Amazon RDS' }); var action = req.body; conn.query('UPDATE actions SET ? WHERE Id = ?',[action,action.Id],function (err,result) { conn.end(); if (err) throw err; res.writeHead(200,{ "Content-Type": "application/json" }); res.end("Updated Successfully"); }); };
我返回“200”,但它总是返回错误子句如下所示:
$.ajax({ url: "/api/action/SaveAction",type: "PUT",data: ko.toJSON(self.stripDownObj()),datatype: "json",contentType: "application/json; charset=utf-8",success: function (result) { console.log(result); if(result.status == 200){ self.isEditMode(!self.isEditMode()); } },error: function(result){ console.log(result); } });
注意:SQL查询是成功的,并且保存数据.
解决方法
当您期待JSON时返回JSON
res.end('{"success" : "Updated Successfully","status" : 200}');
接着
$.ajax({ .... datatype: "json",// expecting JSON to be returned success: function (result) { console.log(result); if(result.status == 200){ self.isEditMode(!self.isEditMode()); } },error: function(result){ console.log(result); } });
在Node中,您可以随时使用JSON.stringify获取有效的JSON
var response = { status : 200,success : 'Updated Successfully' } res.end(JSON.stringify(response));
Express也支持做
res.json({success : "Updated Successfully",status : 200});