Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
Passing User Id to API using Axios Post - Next JS

I am trying to implement that when a user creates a post that their user Id is added to it. Then I want to be able to view all the posts created by a particular user. I am just unsure how to pass the user Id to the api through the axios post request. I am using JWT for authentication so each user is assigned a token and I am using Mongoose/MongoDB so each user has a _id which I would like to assign to their post.

User Schema

const userSchema = new Mongoose.Schema({
email: { type: String},
password: { type: String},
name: { type: String},
createdAt: { type: String},
posts: [{ type: 
Mongoose.Schema.Types.ObjectId, ref:'Post'}]
},{
timestamps: true,
});

Post Schema

const postSchema = new Mongoose.Schema({
name: { type: String},
category: { type: String},
userId: {type: 
Mongoose.Schema.Types.ObjectId, ref:"User"},
},{
    timestamps: true
});

Axios Post Request in pages/createPost

const { data } = await  
axios.post('/api/posts/createPosts', {name, 
category,});
        

Should I be adding a header to this post request?

api/posts/createPosts'

handler.post(async(req, res) => {
await db.connect();




const theNewPost = new Post({
    name: req.body.name,
    category: req.body.category,
})


const thePost = await theNewPost.save();

I have tried console logging req.user._id and req.params.id but both are undefined, of course this is due to me not passing them through in the request so I am just curious as to how this is done? I am looking into storing the user information locally and then accessing it here, or perhaps http-only cookies? Thanks

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda