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

ds97pgxw  于 11个月前  发布在  jQuery
关注(0)|答案(2)|浏览(94)

我的项目在后端有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

h9vpoimq

h9vpoimq1#

代码中包含

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

字符串
如果return语句之后是alert调用,您认为它如何到达alert调用?

unhi4e5o

unhi4e5o2#

你可以使用body-parser来解析JSON数据

import bodyParser from "body-parser";
import express from "express"

const app = express()

app.use(bodyParser.json(options));

// You can replace these options with the available options
// available options are

// - limit
// - revived
// - inflate
// - strict
// - type
// - verify

// example

app.use(bodyParser.json({ limit: "10mb" }));

字符串

相关问题