server.js
uses the body parser middleware, handlebars and express
route
module.exports = function (app) {
app.post('/questionnaire/submit', function (req, res) { // Ajax Call
var data = JSON.parse(req.body);
res.send({});
});
};
client
function submitData() { // Send a data object to the server
$.ajax({
type: 'POST',
url: '/questionnaire/submit',
dataType: "json",
data: JSON.stringify({
satisfactory: "text 1",
improvement: "text 2",
rating: 0.7
})
}).done(function () {
$(location).attr('href', '/sendOff');
}).fail(function () {
});
}
when logging req.body
I get a JSON string
{ '{"satisfactory":"text 1","improvement":"text 2","rating":0.7}': '' }
and I try to parse this string to an object. When I do so, I get this error message
TypeError: Cannot convert object to primitive value at JSON.parse (<anonymous>) at C:\Users\mah\Desktop\FeedbackTool\Server\Routes\questionnaire.js:12:25 at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\mah\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\Users\mah\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5) at C:\Users\mah\node_modules\express\lib\router\index.js:281:22 at Function.process_params (C:\Users\mah\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\mah\node_modules\express\lib\router\index.js:275:10) at C:\Users\mah\node_modules\body-parser\lib\read.js:130:5
so how can I parse the string to an object?
Normally I would execute JSON.parse(req.body)
.