how post request works in server side api in typescript code example
Example 1: how pass data from body in koa js
router.post("/api/comments", async ctx => {
ctx.session.comments = ctx.session.comments || [];
if (!ctx.request.body["comment"]) {
throw Boom.badData("Empty comments not allowed");
}
const comment = {
date: new Date(),
comment: ctx.request.body["comment"],
};
ctx.session.comments.push(comment);
ctx.status = 201;
ctx.body = comment;
});
Example 2: How to send JSON Web Token (JWT Token) as header with Postman and golang
func CreateTokenEndpoint(w http.ResponseWriter, req *http.Request) {
var user User
_ = json.NewDecoder(req.Body).Decode(&user)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username,
})
tokenString, error := token.SignedString([]byte("secret"))
if error != nil {
fmt.Println(error)
}
json.NewEncoder(w).Encode(JwtToken{Token: tokenString})
}