简体   繁体   中英

nodeJS : Route not working Restful API

I'm trying to build an API with node js /express, I have a problem with routing, I cannot get the right route when using express.Router(), here is my code :

this is the server.js file :

//
// ────────────────────────────────────────────────────────────────────────────────────── 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);

this rout not working I dont know what's the problem with that :

routes.get('/api/v1', function(req, res) { res.json({ message: 'Welcome to the coolest API on earth!' }); });

I'm trying to separate the user's route for authentication and signUp, here is the code of user routes :

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; 

在此处输入图片说明 any one can help please ?

You register the /api route before the /api/v1 route.

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!' });
});

Should be

// 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!' });
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM