测试API时,即发送POST请求输出相同的值,但结果应该输出APP_KEY。可能是什么问题?
index.js:
const express = require('express')
const config = require('./config/app')
const router = require('./router')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(router)
const port = config.appPort
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
})
console.log()
路由器/auth.js:
const router = require('express').Router()
const { login, register } = require('../controllers/authController')
router.post('/login', login)
router.post('/register', register)
module.exports = router
控制器/authController.js:
const User = require('../models').User
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
exports.login = async (req, res) => {
const { email, password } = req.body
try {
const secret = require('crypto').randomBytes(64).toString('hex')
//find the user
const user = await User.findOne({
where: {
email
}
})
//check if user found
if (!user) return res.status(404).json({message: 'User not found!'})
//check if password matches
if (!bcrypt.compareSync(password, user.password)) return res.status(401).json({ message: 'Incorect password!' })
//generate auth token
const userWithToken = generateToken(user.get({ raw: true }))
return res.send(secret)
} catch (error) {
return res.status(500).json({ message:e.message })
}
}
exports.register = async (req, res) =>{ }
const generateToken = (user) => {
console.log(user);
delete user.password
const token = jwt.sign(user, 'secret', {expiresIn: 86400})
return { ...user, ...{ token } }
}
路由器/index.js:
const router = require('express').Router()
router.get('/home', (req, res) => {
return res.send('Home screen')
})
router.use('/', require('./auth'))
module.exports = router
结果应该是这样的:
但结果是这样的:
Request: `{
"email": "[email protected]",
"password": "secret"
}`