我的项目在后端有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
型
2条答案
按热度按时间h9vpoimq1#
代码中包含
字符串
如果
return
语句之后是alert
调用,您认为它如何到达alert
调用?unhi4e5o2#
你可以使用body-parser来解析JSON数据
字符串