Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - Express JSON parser cannot respond back

My problem: once I submit a JSON object with JQuery to my express app which uses JSON parser(belongs to the module body-parser) and try to respond back to it, be it res.send or res.render, it does nothing. I try to output html directly back to the client as an html response. On the other hand, on the same page of my website, I tried the regular body parser and the response works fine. Here is my JSON listener:

controller.js:

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended:
false }); 

app.post('/video', jsonParser, function(req, res) {
res.send("hi"); //nothing happens

console.log(req.body.time); //works, i get the data
console.log(req.body.src); //works, i get the data
});

the form that submits to it:

index.html

...mywebsite code, uses jquery
fu();

function fu(){
    var vid = document.getElementById("vid");
    var time = vid.currentTime;
    var src = vid.currentSrc;
    $.ajax({
        type: "POST",
        url: "/video",
        data: JSON.stringify({time: time, src: src  }), //the data is parsed fine
        dataType: 'json',
        contentType: 'application/json'
    });

    //alert("current time: " + time);
};

Now, I have tried a simple form with a body parser and it works fine, on the exact same website(I put it there just to see if it will work):

controller.js

 var express = require('express');
var app = express();

var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended:
false }); 

app.post('/person', urlencodedParser, function(req, res){
    res.send('Thanks!');
    console.log(req.body.firstname);
    console.log(req.body.lastname);    
});

the person form:

      <form method="POST" action="/person">
        Firstname: <input type ="text" id="firstname"
        name="firstname"><br>
        Lastname: <input type ="text" id="lastname"
        name="lastname">
        <input type="submit" value="sumbit">
    </form>     
like image 473
RunningFromShia Avatar asked Jan 18 '26 07:01

RunningFromShia


1 Answers

You need to handle the response in the client after $.ajax request. Set done function to handle success callback:

$.ajax({
        type: "POST",
        url: "/video",
        data: {time: time, src: src  },
        dataType: 'json',
        contentType: 'application/json'
    })
    .done(function( data, status, xhttp) {
         // put the data in the DOM 
         document.getElementById("hi").text(data);
    });
like image 164
leobelizquierdo Avatar answered Jan 20 '26 19:01

leobelizquierdo