nodeJS:路由不工作Restful API

时间:2017-07-17 18:30:49

标签: javascript node.js api express routes

我正在尝试使用节点js / express构建API,我遇到路由问题,使用express.Router()时无法获得正确的路由,这是我的代码:

这是server.js文件:

//
// ────────────────────────────────────────────────────────────────────────────────────── I ──────────
//   :::::: G E T   T H E   P A C K A G E   W E   N E E D : :  :   :    :     :        :          :
// ────────────────────────────────────────────────────────────────────────────────────────────────
//
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');

var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
var User = require('./app/models/User'); // get our mongoose model
var users = require('./app/routes/users')
var routes = express.Router();

//
// ─── CONFIGURATION ──────────────────────────────────────────────────────────────
//

var port = process.env.PORT || 8000; // used to create, sign, and verify tokens
mongoose.connect(config.database, { useMongoClient: true }); // connect to database
app.set('superSecret', config.secret); // secret variable

//
// ─── USE BODY PARSER SO WE CAN GET INFO FROM POST AND/OR URL PARAMETERS ────────────────
//


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//
// ─── USE MORGAN TO LOG REQUESTS TO THE CONSOLE: ────────────────
//

app.use(morgan('dev'));

//
// ──────────────────────────────────────────────────── V ──────────
//   :::::: R O U T E S : :  :   :    :     :        :          :
// ──────────────────────────────────────────────────────────────
//
// ─── BASIC ROUTES──────────────────────────────────────────────────────────────────────
app.get('/app', function(req, res) {
    res.json('Hello! The API is at http://localhost:' + port);
});

// ─── API USER ROUTES──────────────────────────────────────────────────────────────────────
app.use('/api', users);


// route to show a random message (GET http://localhost:8080/api/)
routes.get('/api/v1', function(req, res) {
    res.json({ message: 'Welcome to the coolest API on earth!' });
});

//
// ─── MIDDLEWARE ─────────────────────────────────────────────────────────────────
//
routes.use(function(req, res, next) {

    // check header or url parameters or post parameters for token
    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    // decode token
    if (token) {

        // verifies secret and checks exp
        jwt.verify(token, app.get('superSecret'), function(err, decoded) {
            if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.' });
            } else {
                // if everything is good, save to request for use in other routes
                req.decoded = decoded;
                next();
            }
        });

    } else {

        // if there is no token
        // return an error
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });

    }
});
//
// ────────────────────────────────────────────────── VI ──────────
//   :::::: S T A R T the server: :  :   :    :     :        :          :
// ────────────────────────────────────────────────────────────
//
app.listen(port);
console.log('Magic happens at http://localhost:' + port);

这种溃败不起作用我不知道那是什么问题:

  

routes.get('/ api / v1',function(req,res){   res.json({message:'欢迎来到地球上最酷的API!'});   });

我正在尝试将用户的身份验证和signUp路由分开,这是用户路由的代码:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('../../config'); // get our config file
var User = require('../../app/models/User'); // get our mongoose model
// ─── GET an instance of the router for api routes ────────────────────────────────────────────────────────────────────────
var apiRoutes = express.Router();



apiRoutes.post('/signup', function(req, res) {
    if (!req.body.username || !req.body.password) {
        res.json({ success: false, msg: 'set up required fields' });
    } else {
        var newUser = new User({
            username: req.body.username,
            password: req.body.password
        });
        // save the user
        newUser.save(function(err) {
            if (err) {
                console.log(err);
                return res.json({ success: false, msg: 'Username already exists.' });

            }
            res.json({ success: true, msg: 'Successful created new user.' });
        });
    }
});

apiRoutes.post('/authenticate', function(req, res) {
    User.findOne({
        username: req.body.username
    }, function(err, user) {
        if (err) throw err;

        if (!user) {
            res.send({ success: false, msg: 'Authentication failed. User not found.' });
        } else {
            // check if password matches
            user.comparePassword(req.body.password, function(err, isMatch) {
                if (isMatch && !err) {
                    // if user is found and password is right create a token
                    var token = jwt.sign(user, config.secret);
                    // return the information including token as JSON
                    res.json({
                        success: true,
                        token: token,
                        username: user.username
                    });
                } else {
                    res.send({ success: false, msg: 'Authentication failed. Wrong password.' });
                }
            });
        }
    });
});

apiRoutes.get('/users', function(req, res) {
    User.find({}, function(err, users) {
        res.json(users);
    });
});
module.exports = apiRoutes; 

enter image description here 任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您在> DROP PROCEDURE IF EXISTS `JSON_query_based_on_key`; Query OK, 0 rows affected (0.01 sec) > DELIMITER // > CREATE PROCEDURE `JSON_query_based_on_key`( -> `json` TEXT, -> `key` VARCHAR(5) -> ) -> BEGIN -> DECLARE `sub_things_current` INT -> DEFAULT JSON_LENGTH(`json`, '$.thing.sub_things') - 1; -> -> WHILE (`sub_things_current` > -1) DO -> IF NOT JSON_CONTAINS_PATH( -> `json`, -> 'one', -> CONCAT('$.thing.sub_things[', `sub_things_current`, '].attribute[*]."', `key`, '"') -> ) THEN -> SET `json` := JSON_REMOVE( -> `json`, -> CONCAT('$.thing.sub_things[', `sub_things_current`, ']')); -> END IF; -> SET `sub_things_current` := `sub_things_current` - 1; -> END WHILE; -> -> SELECT JSON_EXTRACT(`json`, '$.thing'); -> END// Query OK, 0 rows affected (0.00 sec) > DELIMITER ; > CALL `JSON_query_based_on_key`('{ '> "thing": { '> "sub_things": [ '> { '> "attribute": [ '> { "1": 40 }, '> { "5": 25 }, '> { "13": 35 } '> ] '> }, '> { '> "attribute": [ '> { "2": 50 }, '> { "7": 50 } '> ] '> } '> ] '> } '> }', '13'); +---------------------------------------------------------------------+ | JSON_EXTRACT(`json`, '$.thing') | +---------------------------------------------------------------------+ | {"sub_things": [{"attribute": [{"1": 40}, {"5": 25}, {"13": 35}]}]} | +---------------------------------------------------------------------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.00 sec) 路线前注册/api路线。

/api/v1

应该是

app.use('/api', users);


// route to show a random message (GET http://localhost:8080/api/)
routes.get('/api/v1', function(req, res) {
    res.json({ message: 'Welcome to the coolest API on earth!' });
});