我在快递中遇到路由冲突。我已经按照我认为正确的顺序放置了路线:从简单到高级。 IE:['/',get('/ api'),post('/ api / add'),get('/ api /:id')]。
但是显然我的代码还有其他想法。
错误:
result = ret[0]; TypeError: Cannot read property '0' of undefined
^
server.js
const express = require('express');
const bodyParser = require('body-parser');
const swig = require('swig');
swig.setDefaults({cache:false});
const sqlite3 = require('sqlite3');
const db= new sqlite3.Database('./database.db', (err)=> console.log(err));
const app = express();
app.use(express.static("static_files"));
app.use(bodyParser.urlencoded({extended:false}));
app.set('view engine', 'html');
app.engine('html', swig.renderFile);
//disableinproduction//
app.set('viewcache', false);
/*---------------------------Here Be Routes--------------------------------*/
//Whether or not this or req.params.id is used, doesn't change the problem.
app.param('id', function( req, res, next, id ) {
req.id_from_param = id;
next();
});
//works like a charm
app.get('/', (req, res, next)=>{
res.send('Works Fine');
});
//Works JUST FINE
app.get('/api', (req, res, next)=>{
db.all("select * from Reports", (err, ret) => {
console.log(ret);
console.log(err);
res.render('index', { results:ret, error:err });
});
});
//DOESN'T WORK
app.post('/api/add', (req, res, next) => {
res.send('this is supposed to work BUT DOESN'T!');
});
//Where I get the error from
app.get('/api/:id', (req, res, next)=>{
db.all(`select * from Reports where id = ${req.id_from_param}`, (err, ret) => {
console.log(`GETting report for report id: ${req.id_from_param}`);
result = ret[0];
//(!ret) ? console.log(`This report does not exist.${err}`):console.log(ret);
//console.log(err);
res.render('edit', { editbtn:false, results:result, error:err });
console.log(result);
//res.send('EditPage');
});
});
router.put('/api/:id', (req, res, next) => {
res.send(`Under Construction. ID: ${req.id_from_param}`);
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port: ${port}`));
似乎我有与此完全相同的问题:Express parameterized route conflict,但我的加载顺序似乎正确。 有谁知道为什么我要加载参数化路由而不是/ api / add?