无法从使用Typescript编码的NodeJS服务器返回JSON数据

时间:2013-12-14 07:52:12

标签: jquery express typescript

我的项目后端有NodeJS + Express,它必须将JSON数据作为对JQuery前端的POST响应返回。由于某种原因,消息没有到达前端 - whcih使用JQuery AJAX调用。虽然我不完全确定它的中断位置,因为前端代码应该显示一条警告消息,无论呼叫是失败还是成功,但都没有显示消息。

服务器:

// <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
    }));
});

客户端:

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();
        }
    });
}

控制台消息:

Body called
123
Sending response

1 个答案:

答案 0 :(得分:1)

您的代码包含

return JSON.parse(responseData);
alert("success");

如果在alert声明之后,您认为它如何能够达到return来电?