My project involves using NodeJS + Express on the back end to send JSON data as a POST response to the front end through JQuery. I'm facing an issue where the message is not reaching the front end, which utilizes a JQuery AJAX call. It's puzzling because the front end code is designed to display an alert message whether the call fails or succeeds, but nothing shows up.
Here is the server-side code:
// <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
}));
});
This is the client-side code:
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 output:
Body called
123
Sending response