RunningFromShia
RunningFromShia

Reputation: 610

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>     

Upvotes: 3

Views: 223

Answers (3)

Slava Melnik
Slava Melnik

Reputation: 103

You may try polyfill "fetch" instead jQuery:

function getResponse (url) {
  return fetch(url, {
      method: 'post',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ time, src })
      })
      .then(response => response.json())
      .then(data => {
        console.log('request succeeded with JSON response', data)
      })
      .catch(error => {
        console.log('request failed', error)
      })
}

I think it will look much better. And it can be used on server side. Docs: https://github.com/github/fetch

Upvotes: 0

leobelizquierdo
leobelizquierdo

Reputation: 1668

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);
    });

Upvotes: 1

Dawid Pura
Dawid Pura

Reputation: 1029

Hm, looks pretty easy - you are not using jsonParser in the second snippet - just urlencodedParser, which is not correct here. So it should looks like here:

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', jsonParser, function(req, res){
    res.send('Thanks!');
    console.log(req.body.firstname);
    console.log(req.body.lastname);    
});

Upvotes: 0

Related Questions