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>
stringifydata you send to server. Try:data: {time: time, src: src }instead.dataType: 'json'but you send plain text in response. Also, catching the response to any variable would be useful I believe. Currently your AJAX request does nothing with it.