Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to return JSON data from NodeJS server coded using Typescript

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
like image 556
EternallyCurious Avatar asked Aug 15 '26 04:08

EternallyCurious


1 Answers

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?

like image 170
6502 Avatar answered Aug 17 '26 17:08

6502



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!