0

Once I have filled out input, I would like to send it in JSON via AJAX to server. However, upon sending the data, the server says ValidationError: Post validation failed: text: Path 'text' is required.. When I console.log(req.body.post) on the server, it says undefined. I try to find out what's wrong but still not able to resolve it.

HTML

<form action="/main/messages" id="homePagePostForm">
   <input type="text" class="form-control" id="homePagePostInput" name="post[text]">
   <input type="button" id="homePagePostInputButton" style="display:none">
</form>

AJAX

$.ajax({
    url: "/main/home",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({
        post:{"text": $("#homePagePostInput").val()}
    });
})

NodeJS/Mongoose

router.post("/main/home", function(req, res){
    User.findById(req.user._id, function(err, currentUser){
        if(err){
            console.log(err);
        } else {
            //it says undefined for req.body.post
            console.log(req.body.post)
            Post.create(req.body.post, function(err, post){
                if(err){
                    console.log(err);
                    //request made it ways here, and ends here. 
                    res.redirect("/main/home");
                } else {
                    ......

Post's Schema

var postSchema = mongoose.Schema({
    text: {type: String, required: true},
    date: Date,
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    },
    likes: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        }
    ],
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Comment"
        }
    ]
});
2
  • Are you using body-parser or any other middleware to parse your stringified data? Commented Mar 12, 2018 at 12:21
  • Yes I use body-parser. Commented Mar 12, 2018 at 12:29

1 Answer 1

0

The error has nothing to do with mongoose since your req.body.post is undefined.

Double check your network tab, and see if the POST body is actually set and sent with the correct format. If yes, then the problem is in your API, double check the URL and the required params.

Also, it seems that your POST API is called /main/home but then you use a redirect to the same URL /main/home which in case of success of the initial call, will re-call this API without a POST.

These are just some hints to fix your problem.

Sign up to request clarification or add additional context in comments.

4 Comments

When I console.log(JSON.stringify({post:{"text":$("#homePagePostInput").val()}})) on the browser, it shows {"post":{"text":"123"}}. I then switch to normal form POST method (no AJAX), and then console.log(req.body) on the server. It shows { post: { text: '123' } }. However, when I use AJAX to send the same data, upon console.log(req.body) on the server it shows {}. So I guess the format is correct, but the data is not being send from the browser via AJAX, thus causing undefined?
Check out this link : stackoverflow.com/questions/15042245/… Maybe try to add dataType: "json" or try to send the data without JSON.stringify since you said you are using body parser (it should do it for you).
Thanks for the link. There is an answer that suggests to include app.use(bodyParser.json()) which has helped me. I think it's because that the data is JSON so it won't be parsed unless I include that code.
Ok I thought you were already using the bodyParser.json() (from your previous comments). Well if it's fixed for you, you can close this discussion :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.