无法使路由在Node.js中工作

时间:2018-08-10 11:25:59

标签: node.js routing

运行node server.js命令后,server.js代码就是这一代码 我能够访问http://localhost:8080/并正确获取json

{"error":false,"data":[{"id":1,"task":"Find bugs","status":1,"created_at":"2016-04-10T18:20:40.000Z"},{"id":2,"task":"Review code","status":1,"created_at":"2016-04-10T18:20:40.000Z"},{"id":3,"task":"Fix bugs","status":1,"created_at":"2016-04-10T18:20:40.000Z"},{"id":4,"task":"Refactor Code","status":1,"created_at":"2016-04-10T18:20:40.000Z"},{"id":5,"task":"Push to prod","status":1,"created_at":"2016-04-10T18:20:50.000Z"}],"message":"Todos list."}

但是当我尝试访问http://localhost:8080/secret时,出现“无法获取/ secret”错误。我的server.js文件就是这个

const express = require('express');
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended:true 
}));
const mc = mysql.createConnection({
host:'localhost',
user : 'root',
password : '',
database : 'task'
});
mc.connect();

// Retrieve all todos 

//default route
app.all('/',function(req,res,next){

     mc.query('SELECT * FROM tasks', function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Todos list.' });
        next()
    });
     });
 app.use('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...')
  next() // pass control to the next handler
})
app.listen(8080,function(){

    console.log('Node app is running on port 8080');
});

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

您现在的实施似乎还不完整。您应该检出express.Router documentation(检出页面的底部)。

您尝试使用的use方法应至少包含一个router.get('/', function (req, res) {} );实现。或者,您可以将use替换为getall,它将起作用。

祝你好运!

答案 1 :(得分:0)

您应该使用get而不是全部,并且不需要下一个功能。尝试以下方法。

app.get('/', function (req, res) {
    mc.query('SELECT * FROM tasks', function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Todos list.' });
    });
});