nodejs app get 提交了两次请求
发布于 11天前 作者 helloedmund 399 次浏览 最后一次编辑是 2天前 来自 问答

app.js

var express = require("express")
var path = require('path')
var mongoose = require('mongoose')
var _ = require('underscore')
var Movie = require('./models/movie')
var port = process.env.PORT || 3000
var app = express()
var bodyParser = require('body-parser');

mongoose.connect('mongodb://localhost:27017/imooc_projects')

app.set('views', './views/pages')
app.set('view engine', 'jade')
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'bower_components')))
app.listen(port)

console.log('imooc started on port ' + port);

index page

app.get('/', function (req, res) {
    Movie.fetch(function(err, movies) {
        if (err){
            console.log(err)
        }

        res.render('index', {
            title: 'imooc 首页',
            movies: movies
        })
    })
})

detail page

app.get('/movie/:id', function (req, res) {
    var id = req.params.id

    console.log("putain")
    console.log(id)

    Movie.findById(id, function(err, movie) {

            
        console.log(movie)

        res.render('detail', {
            title: 'imooc' + movie.title,
            movie: movie
        })
    })
})

admin page

app.get('/admin/movie', function (req, res) {
    res.render('admin', {
        title: 'imooc 后台录入页',
        movie: {
            director: '',
            country: '',
            title: '',
            year: '',
            poster: '',
            language: '',
            flash: '',
            summary: ''
        }
    })
})

admin update movie

app.get('/admin/update/:id', function(req, res) {
    var id = req.params.id

    if (id) {
        Movie.findById(id, function(err, movie) {
            res.render('admin', {
                title: 'imooc 后台更新页',
                movie: movie
            })
        })
    }
})

admin post movie

app.post('/admin/movie/new', function(req, res) {
    var id = req.body.movie._id
    var movieObj = req.body.movie
    var _movie


    console.log(id)

    if (id !== undefined) {
        Movie.findById(id, function(err, movie) {
            if (err) {
                console.log(err)
            }
            console.log("alkfoaj1")
            _movie = _.extend(movie, movieObj)
            //console.log(movie)
            //console.log(movieObj)
            //console.log(_movie)
            //console.log("alkfoaj2")
            _movie.save(function(err, movie) {
                if (err) {
                    console.log(err)
                }
            //console.log("alkfoaj3")
                res.redirect('/movie/' + movie._id)
            })
        })
    }
    else {

        console.log("else")
        _movie = new Movie({
            director: movieObj.director,
            title: movieObj.title,
            country: movieObj.country,
            language: movieObj.language,
            year: movieObj.year,
            poster: movieObj.poster,
            summary: movieObj.summary,
            flash: movieObj.flash
        })

        _movie.save(function(err, movie) {
            if (err) {
                console.log(err)
            }

            //console.log(movie._id + "a")
            res.redirect('/movie/' + movie._id)
        })
    }
})

list page

app.get('/admin/list', function (req, res) {
    Movie.fetch(function(err, movies) {
        if (err){
            console.log(err)
        }

        res.render('list', {
            title: 'imooc 列表页',
            movies: movies
        })
    })
})

movie.js

var mongoose =require ('mongoose')

var MovieSchema = new mongoose.Schema({
    director: String,
    title: String,
    language: String,
    country: String,
    summary: String,
    flash: String,
    poster: String,
    year: Number, 
    meta:{
        createAt:{
            type: Date,
            default: Date.now()
        },
        updateAt:{
            type: Date,
            default: Date.now()
        }
    }
})


MovieSchema.pre('save',function(next) {
    if(this.isNew){
        this.meta.createAt = this.meta.updateAt = Date.now();
    }
    else{
        this.meta.updateAt = Date.now()
    }

    next()

    //console.log("aa")
})



MovieSchema.statics = {
    fetch: function(cb){
        return this
            .find({})
            .sort('meta.updateAt')
            .exec(cb)
    },
    findById: function(id, cb){
        //console.log("aaa")
        return this
            .findOne({_id: id})`enter code here`
            .exec(cb)
    }
}

module.exports = MovieSchema

admin.jade

extend ../layout

block content
    .container
        .row
            form.form-horizontal(method="post",action="/admin/movie/new")
                //-input(type="hidden", name="movie[_id]", value="#{movie._id}")
                .form-group
                    label.col-sm-2.control-label(for="inputTitle") 电影名字
                    .col-sm-10
                        input#inputTitle.col-sm-10.form-control(type="text",name="movie[title]",value="#{movie.title}")
                .form-group
                    label.col-sm-2.control-label(for="inputDirector") 电影导演
                    .col-sm-10
                        input#inputDirector.col-sm-10.form-control(type="text",name="movie[director]",value="#{movie.director}")
                .form-group
                    label.col-sm-2.control-label(for="inputCountry") 国家
                    .col-sm-10
                        input#inputCountry.col-sm-10.form-control(type="text",name="movie[country]",value="#{movie.country}")
                .form-group
                    label.col-sm-2.control-label(for="inputLanguage") 语种
                    .col-sm-10
                        input#inputLanguage.col-sm-10.form-control(type="text",name="movie[language]",value="#{movie.language}")
                .form-group
                    label.col-sm-2.control-label(for="inputPoster") 海报地址
                    .col-sm-10
                        input#inputPoster.col-sm-10.form-control(type="text",name="movie[poster]",value="#{movie.poster}")
                .form-group
                    label.col-sm-2.control-label(for="inputFlash") 片源地址
                    .col-sm-10
                        input#inputFlash.col-sm-10.form-control(type="text",name="movie[flash]",value="#{movie.flash}")
                .form-group
                    label.col-sm-2.control-label(for="inputYear") 上映年份
                    .col-sm-10
                        input#inputYear.col-sm-10.form-control(type="text",name="movie[year]",value="#{movie.year}")
                .form-group
                    label.col-sm-2.control-label(for="inputSummary") 电影简介
所得结果如下:

QQ截图20151023085625.png

也就是这段代码执行了两次: 2.png

小弟初学,不知道这是什么情况为什么会get 两次(PS: 话说在CNODEJS上提问,搞了半天不知道怎么排版代码,希望各位大大能顺便告知下谢谢)

9 回复

大哥,自己定位好问题之后,把一小段关键示例放上来就好了。把 mongoose 的配置也放上来太没有诚意了

@alsotang 刚学nodejs, 只是照着mooc上的代码,具体啥意思也不是很明白…所以就这样了~~望见谅!(话说这是啥问题呀,纠结了好久问题还没解决)

不是不想帮你看,实在是你贴的东西没法看。 执行多次基本都是定义了重复路由,比如你定义了

app.get('/movie/:id', function(req, res, next) {
    //business loginc
    next();
})

app.get('/movie/news', function(req, res, next) {
    //business loginc
    var rtn = {};
    return res.json(rtn);
});

那么当你请求 GET /movie/news的时候/movie/:id也会执行的

你这迷の语法高亮。。 建议你查查浏览器发出的http request,看看有没有额外的请求

@ruanyl 还有迷之代码缩进

这个我晕,刚开始看了两行,然后…就没有人然后了 代码格式化,从零开始,半个小时也能搞定。如果表单提交两次,最简单方法,第一次提交之后立刻禁用按钮,等响应返回让回复按钮,reset表单

想问楼楼这个问题解决了么?刚刚我也遇到了,发现引入db.findById之后就会多出一次请求。。路由也没有重复定义,求解

@Deacyn 把detail.jade 中的 movie.flash 那行注释了

回到顶部