当我使用POST ajax函数时,我遇到了一个问题。
我正在运行一个由express-generator使用node,express,mongodb,mongoose和jade创建的简单app。在我创建了一个用于将新对象发布到数据库的模块之后,我注意到POST / DELETE请求已多次完成。这种情况在'on-click'模式下发生,如果我将功能更改为在加载时自动加载。
请注意:该功能仅由用户调用一次 - 浏览器中没有日志。看起来它每2分钟运行一次,我完全不知道为什么。
非常感谢任何帮助。
Javascript代码:
$('#btn5').on('click', saveFiveDayForecast);
saveFiveDayForecast = function() {
var random = {
city: 'One'
}
$.ajax({
type: 'post',
data: JSON.stringify(random),
url: '/fiveDay/',
contentType: 'application/json',
dataType: 'JSON'
})
}
路由文件:
var express = require('express');
var router = express.Router();
// DB schema and model setup ----------------------------------------------
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create 16 day schema
var fiveDaySchema = new Schema({
city : String
}, { collection: 'fiveDayModel' });
// create 16 day model for later manipulation in routing files
var fiveDayModel = mongoose.model('fiveDayModel', fiveDaySchema);
// END DB schema and model setup -------------------------------------------
/* POST */
router.post('/', function(req, res) {
var time = new Date();
var fiveDayWeatherToSave = new fiveDayModel( req.body );
console.log('post in the routing file was fired at: ');
console.log(time);
fiveDayWeatherToSave.save(function (err, data) {
if (err) console.log(err);
else console.log('Saved ', data );
});
});
来自节点的日志:
节点日志很有意思:第一次保存数据时,其中没有POST行,但数据仍然保存。
post in the routing file was fired at:
Wed May 13 2015 14:40:06 GMT+0100 (GMT Daylight Time)
Saved { __v: 0, city: 'One', _id: 55535436f0ee99bc1d790220 }
POST /fiveDay/ - - ms - -
post in the routing file was fired at:
Wed May 13 2015 14:42:06 GMT+0100 (GMT Daylight Time)
Saved { __v: 0, city: 'One', _id: 555354aef0ee99bc1d790221 }
POST /fiveDay/ - - ms - -
答案 0 :(得分:0)
如果请求因超时而失败,浏览器将重试该请求。由于您永远不会返回响应,因此始终会发生这种情况。您应该回复res.end()
或res.send("success!")
。