我试图将我的php页面中的一些数据发布到我的node.js服务器上。我希望得到它的响应。
这是我从我的php页面发送的ajax代码,目前正在apache服务器上执行
function encryptCode()
{
var value = document.getElementById("code").value;
$.ajax({
url: "http://localhost:3000/insertUser",
type: "POST",
data: JSON.stringify(value),
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data)
{
alert(data);
}
});
}
我只想通过此代码在我的node.js页面中接收它
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "insertUser",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
console.log(data);
/*this.getContent(function() {
// var v = new View(res, 'place');
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(self.content));
});*/
// console.log("go to hell");
},
});
这是我的express.js的控制器,我已经从我的app.js页面重定向了这段代码
app.all('/insertUser', attachDB, function(req, res, next) {
insertUser.run( req, res, next);
});
有人请帮我在console.log中得到{} .....
答案 0 :(得分:0)
首先测试是前端的问题。
function encryptCode()
{
var value = document.getElementById("code").value;
console.log(value);
$.ajax({
url: "http://localhost:3000/insertUser",
type: "POST",
data: {"user":value},
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data)
{
alert(data);
}
});
}
您应该在快速应用中设置json body解析器
var app = express();
bodyParser = require('body-parser');
app.use(bodyParser.json());
你在哪里宣布data
变量。在node.js中,通过ajax请求发送的数据可在req.body
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "insertUser",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
console.log(req.body);
// console.log(req.body.user);
},
});