Код: Выделить всё
app.get("/posts", authentificationToken, (req, res) => {
if(posts.filter(post => post.username !== req.username))
res.json({ "message": "you have yet to upload posts"})
else {
res.json(posts.filter(post => post.username === req.user.name))
}
})
function authentificationToken(req, res, next) {
const authHeader = req.headers["authorization"]
const token = authHeader && authHeader.split(" ")[1]
if(token == null) return res.status(401).send({error: "unauthorized"})
jwt.verify(token, ACCESS_TOKEN_SECRET, (err, user) => {
if(err) return res.status(403).send({ error: "forbidden"})
req.user = user
next()
})
}
Для контекста ниже указан порядок этого конкретного запроса на публикацию.
В моем файле сервера у меня есть:
Код: Выделить всё
app.get("/posts", postsRoutes)
Код: Выделить всё
postsRoutes.post("/login", handleposts)
Мой контроллер с handleposts выглядит следующим образом:
Код: Выделить всё
//normally authentifcationToken would be in a util but for convenience i have left it inside the controller
export const authentificationToken = function(req: RequestCustomer, res: Response, next: NextFunction) {
const authHeader = req.headers["authorization"]
const token = authHeader && authHeader.split(" ")[1]
if(token == null) return res.status(401).send({error: "unauthorized"})
jwt.verify(token, ACCESS_TOKEN_SECRET, (err, user) => {
if(err) return res.status(403).send({ error: "forbidden"})
req.user = user
next()
})
}
export const handleposts = catchErrors(
async(req, res) => {
// validate the request
const request = postSchema.parse({
...req.body,
userAgent: req.headers["user-agent"]
})
// call the service
const posts = await getPosts(request)
// return the response
return res.status(CREATED).json(posts)
}
)
Ниже приведены мои getPosts:
Код: Выделить всё
export const getPosts = async(data: PostRequest) => {
if(posts.filter(post => post.username !== data.username))
return ({ "message": "you have yet to upload posts"})
else {
const post_result = posts.filter(post => post.username === data.username)
return post_result
}
}
Я также упоминал о объединении нескольких частей промежуточного программного обеспечения для определенного маршрута в ExpressJS, но мне не удалось перевести это в мою структуру обработки запроса.
Я сослался на Экспресс-документация, но здесь также добавляется промежуточное программное обеспечение в стандартном app.get("/", middleware, function()).
Подробнее здесь: https://stackoverflow.com/questions/798 ... -structure
Мобильная версия