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"
        }
    ]
});
Steven
  • 75
  • 9

1 Answers1

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.

HRK44
  • 2,382
  • 2
  • 13
  • 30
  • 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`? – Steven Mar 14 '18 at 06:19
  • Check out this link : https://stackoverflow.com/questions/15042245/reading-ajax-post-variables-in-node-js-with-express 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). – HRK44 Mar 14 '18 at 08:22
  • 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. – Steven Mar 14 '18 at 11:22
  • 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 :) – HRK44 Mar 14 '18 at 13:31