确定后端能获取token,也已经登录了,但前端console报401,message是Not Found,视频重复看几遍了,完全是跟这些,麻烦老师帮看看吧,以下是代码:
const User = require(’…/models/users’);
const jwt = require(‘jsonwebtoken’);
const { secret } = require(’…/config’);
class UserCtrl {
async find(ctx) {
ctx.body = await User.find();
}
async findById(ctx) {
const { fields } = ctx.query;
const user = await User.findById(ctx.params.id);
if(!user) {
ctx.throw(404, '用户不存在');
}
ctx.body = user;
}
async create(ctx) {
ctx.verifyParams({
username: { type: 'string', required: true },
password: { type: 'string', required: true }
});
const { username } = ctx.request.body;
const repeatedUser = await User.findOne({ username });
if(repeatedUser) {
ctx.throw(409, '用户已经存在')
}
const user = await new User(ctx.request.body).save();
ctx.body = user;
}
async checkOwner(ctx, next) {
console.log('check')
if(ctx.params.id !== ctx.state.user._id) {
ctx.throw(403, '沒有權限');
}
await next();
}
async update(ctx) {
console.log('update')
ctx.verifyParams({
username: { type: 'string', required: false },
password: { type: 'string', required: false },
avatar_url: { type: 'string', required: false },
gender: { type: 'string', required: false },
headline: { type: 'string', required: false },
locations: { type: [{ type: String }] },
business: { type: 'array', itemType: 'object', required: false },
educations: { type: 'array', itemType: 'object', required: false },
})
const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body)
if(!user) {
ctx.throw(404, '无此用户')
}
ctx.body = user
}
async delete(ctx) {
ctx.status = 204
}
async login(ctx) {
ctx.verifyParams({
username: { type: 'string', required: true },
password: { type: 'string', required: true }
})
const user = await User.findOne(ctx.request.body);
if(!user) {
ctx.throw(401, '用戶名或密碼不正確');
}
const { _id, username } = user;
const token = jwt.sign({ _id, username}, secret, {expiresIn: '1d'});
ctx.body = { token };
}
}
module.exports = new UserCtrl();
===================================
const Router = require(‘koa-router’);
const router = new Router({prefix: ‘/users’});
const { find, findById, create, delete:del, update, login, checkOwner } = require(’…/controllers/user’);
const jwt = require(‘koa-jwt’);
const { secret } = require(’…/config’);
const auth = jwt({
secret
});
router.get(’/’, find);
router.post(’/’, create);
router.get(’/:id’, findById);
router.patch(’/:id’, auth, checkOwner, update);
router.delete(’/:id’, auth, checkOwner, del);
router.post(’/login’, login);
module.exports = router;