Issue
My project has NodeJS + Express in the back end that has to return JSON data as a POST response to the front end in JQuery. For some reason the message does not reach the front end - whcih uses JQuery AJAX call. Although I'm not entirely sure where its breaking, because the front end code is supposed to show an alert message whether the call fails or succeeds, but no message is shown.
Server:
// <reference path="lib/Main.d.ts" />
import express = require('express');
import http = require('http');
import path = require('path');
import fs = require('fs');
var routes = require('./routes');
var user = require('./routes/user');
var formidable = require('formidable');
var app = express();
app.use(express.logger());
// all environments
app.set('port', process.env.PORT || 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
/**
* Receives JSON Data
*/
app.post("/data", function (request, response){
console.log("Body called");
var x = String(request.body.test);
console.log(x);
console.log("Sending response");
var resp = "Received " + x;
response.send(JSON.stringify({
message : resp
}));
});
Client:
function start() {
send({
test: 123
},function test(responseData){
alert(responseData);
}
)
}
function send(data : any, success:(String) => void){
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: '/data',
success: function (responseData) {
var x = JSON.parse(responseData);
alert("success");
success(x.body.message);
},
error: function(err){
alert("failure");
var e = serverCommunicationFailureError();
e.displayErrorMessage();
}
});
}
Console Message:
Body called
123
Sending response
Solution
Your code contains
return JSON.parse(responseData);
alert("success");
How do you think it can reach the alert
call if that is after a return
statement?
Answered By - 6502
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.