2017-07-17 63 views
0

我想建立一個API與節點js/express,我有一個路由問題,我無法得到正確的路線,當使用express.Router(),這裏是我的代碼:nodeJS:路由不工作Restful API

這是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',函數(req,res)res.json({message:'Welcome to th世界上最酷的API!')); });

我試圖進行身份驗證和註冊分隔用戶的路線,這裏是用戶路徑的代碼:

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 任何一個可以幫助嗎?

回答

0

您在/api/v1路線之前註冊/api路線。

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

應該

// 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); 
+0

感謝您的幫助,但我得到了同樣的錯誤:無法獲取/ API/V1! – sahnoun