'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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
