2017-09-04 70 views
0

我想爲我的一個實踐項目製作一個小型認證系統。我正嘗試通過郵遞員將POST請求發送到我的快遞服務器(http://localhost:4000/api/register),並且它回覆「404找不到」我正在按照教程here爲什麼我的Express api註冊路由不是POSTing?

這裏是我的server.js:

const newpost = require('./routes/newpost'); 
const getposts = require('./routes/getposts'); 
const express = require('express'); 
const bodyParser = require('body-parser'); 
const cors = require('cors'); 
const deleteposts = require('./routes/delete'); 
const editposts = require('./routes/editposts'); 
const path = require('path'); 

const app = express(); 
const webpack = require('webpack'); 
const webpackConfig = require('../webpack.config'); 
const webpackMiddleware = require('webpack-dev-middleware'); 
const webpackHotMiddleware = require('webpack-hot-middleware'); 
const passport = require('passport'); 

const port = 4000; 
const compiler = webpack(webpackConfig); 
const config = require('./config/main'); 
const mongoose = require('mongoose'); 
const authRouter = require('./routes/authrouter'); 
const logger = require('morgan'); 


// db connection 
mongoose.connect(config.database); 

app.use(passport.initialize()); 
/* 

app.use(webpackMiddleware(compiler, { 
    noInfo: true, publicPath: webpackConfig.output.publicPath, 
})); 

app.use(webpackHotMiddleware(compiler, { 
    log: console.log, 
})); 

*/ 
app.use(cors()); 
// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false })); 
// parse application/json 
app.use(bodyParser.json()); 
app.use(logger('dev')); 


app.use('/newpost', newpost); 
app.use('/posts', getposts); 
app.use('/delete', deleteposts); 
app.use('/edit', editposts); 
//auth router to handle auth routes 
authRouter(app); 


/* 
app.get('/*', (req, res) => { 
    res.sendFile(path.join(__dirname, '../public/index.html')); 
}); */ 

app.listen(port,() => { 
    console.log(`Listening on port ${port}`); 
}); 

這是我authrouter.js。這些是我輸出到我的server.js中的路線。 :

const AuthenticationController = require('../controllers/authentication'); 
const express = require('express'); 
// const passportService = require('../config/passport'); 
/* eslint-disable */ 

const passport = require('passport'); 

// Middleware to require login/auth 
// const requireAuth = passport.authenticate('jwt', { session: false }); 
const requireLogin = passport.authenticate('local', { session: false }); 


module.exports = function(app){ 
    "use-strict"; 
    // init route groups 
    const apiRoutes = express.Router(); 
    const authRoutes = express.Router(); 

    // auth routes 
    // set auth routes as subgroup/middleware to apiRoutes 
    apiRoutes.use('/auth', authRoutes); 

    // Registration routes 
    authRoutes.post('/register', AuthenticationController.register); 

    // Login route 
    authRoutes.post('/login', requireLogin, AuthenticationController.login); 

    // Set url for API group routes 
    app.use('/api', apiRoutes); 
}; 

這裏是我的authentication.js

const jwt = require('jsonwebtoken'); 
// const crypto = require('crypto'); used for pw resets 
const User = require('../models/user'); 
const config = require('../config/main'); 

function generateToken(user) { 
    return jwt.sign(user, config.secret, { 
    expiresIn: 10080, // in seconds 
    }); 
} 

// set user info from request 
function setUserInfo(request) { 
    return { 
    _id: request._id, 
    email: request.email, 
    role: request.role, 
    }; 
} 

// Login Route 
exports.login = function (req, res, next) { 
    const userInfo = setUserInfo(req.user); 

    res.status(200).json({ 
    token: `JWT${generateToken(userInfo)}`, 
    user: userinfo, 
    }); 
}; 

// registration route 
exports.register = function (req, res, next) { 
// check for registration errors 

    const email = req.body.email; 
    const password = req.body.password; 

    // Return error if no email provided 
    if (!email) { 
    return res.status(422).send({ error: 'You must enter an email address' }); 
    } 

    // Return error if no pw provided 
    if (!password) { 
    return res.status(422).send({ error: 'You must enter a password' }); 
    } 

    User.findOne({ email }, (err, existingUser) => { 
    if (err) { return next(err); } 

    // if user is not unique, return error 
    if (existingUser) { 
     return res.status(422).send({ error: 'That email address is already in use' }); 
    } 

    // if email is unique and pw was provided, create acct 
    const user = new User({ 
     email, 
     password, 
    }); 

    user.save((err, user) => { 
     if (err) { return next(err); } 

     // Subscribe member to Mailchimp list 
     // mailchimp.subscribeToNewsLetter(user.email); 
     // Respond with JWT if user was created 

     const userInfo = setUserInfo(user); 

     res.status(201).json({ 
     token: `JWT ${generateToken(userInfo)}`, 
     user: userInfo, 
     }); 
    }); 
    }); 
}; 

// Role authorization check 
exports.roleAuthorization = function (role) { 
    return function (req, res, next) { 
    const user = req.user; 

    User.findById(user._id, (err, foundUser) => { 
     if (err) { 
     res.status(422).json({ error: 'No user was found' }); 
     return next(err); 
     } 

     // if user is found, check role 
     if (foundUser.role == role) { 
     return next(); 
     } 

     res.status(401).json({ error: 'You are not authorized to view this content ' }); 
     return next('Unauthorized'); 
    }); 
    }; 
}; 

這裏是我的passport.js:

// Importing Passport; strategies; and config 
const passport = require('passport'); 
const User = require('../models/user'); 
const config = require('./main'); 
const JwtStrategy = require('passport-jwt').Strategy; 
const ExtractJwt = require('passport-jwt').ExtractJwt; 
const LocalStrategy = require('passport-local'); 

const localOptions = { usernameField: 'email' }; 

// setting up the local Strategy 
const localLogin = new LocalStrategy(localOptions, ((email, password, done) => { 
    User.findOne({ email }, (err, user) => { 
    if (err) { return done(err); } 
    if (!user) { 
     return done(null, false, { error: 'Your login details could not be verified. Please try again.', 
     }); 
    } 
    user.comparePassword(password, (err, isMatch) => { 
     if (err) { return done(err); } 
     if (!isMatch) { 
     return done(null, false, { error: 'Your login details could not be verified. Please try again.', 
     }); 
     } 

     return done(null, user); 
    }); 
    }); 
})); 

const jwtOptions = { 
    // Telling passport to check auth headers for JWT 
    jwtFromRequest: ExtractJwt.fromAuthHeader(), 
    // Telling passport where to find the secret 
    secretOrKey: config.secret, 
}; 

// setting up JWT login strategy 
const jwtLogin = new JwtStrategy(jwtOptions, ((payload, done) => { 
    User.findById(payload._id, (err, user) => { 
    if (err) { return done(err, false); } 

    if (user) { 
     done(null, user); 
    } else { 
     done(null, false); 
    } 
    }); 
})); 
// allow passport to use the strategies we defined 
passport.use(jwtLogin); 
passport.use(localLogin); 

回答

1

我相信正確的後端點將API /認證/註冊