javascript - 这个方法/函数如何被调用两次?
问题描述
我只是通过代码直接向数据库发送一些数据,只是为了测试我的数据库连接。所以时机是使用 GET 方法而不是 POST。这是我的代码:
const express = require('express');
const router = express.Router();
const db = require('../config/database');
const Gig = require('../models/Gig');
const Sequelize = require('sequelize');
const favicon = require('express-favicon');
next();
//Get the gig list
router.get('/', (req, res) =>
Gig.findAll()
.then(gigs => {
console.log(gigs);
console.log('Looks like no error!!!!');
res.sendStatus(200);
})
.catch(err => console.log('ERROR in routes/gigs.js: >> '+err)));
//Add data to database
router.get('/add', (req, res, next) => {
const data = {
title: 'Full Stack Developer',
technologies: 'Node.js, React.js, MongoDB, PostgreSQL, Android, iOS, Wed Development',
budget: '$5000',
description: 'Since established in 1995, Bluebird Inc. has developed constantly together with our partners as the leading provider of the mobile computer.'+
'We have always released innovative products timely to market that meet the expanding needs of our customers,'+
'which is the essential factor to success in a mobile computing business',
contact_email: 'hr@comapany.com'
}
let { title, technologies, budget, description, contact_email } = data;
//To insert data
Gig.create({
title,
technologies,
budget,
description,
contact_email
})
.then(gig => {
console.log(gig);
res.redirect('/gigs');
res.send();
return next();
})
.catch(err => console.log('ERROR while inserting in routes/gigs.js: >> '+err));
});
module.exports = router;
问题是上面的函数被执行了两次。一旦将数据发送到数据库,我不知道如何停止它或结束该功能。
更多代码:
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const path = require('path');
const db = require('./config/database');
db.authenticate()
.then(() => console.log('Database Connected...'))
.catch(err => console.log('ERROR:>> '+err));
const app = express();
app.get('/', (req, res) => res.send('INDEX'));
//Get routes
app.use('/gigs', require('./routes/gigs'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));