我试图将一些数据从我的 php 页面发布到我的 node.js 服务器。我想从中获取响应。
这是我从当前在 apache 服务器上执行的 php 页面发送的 ajax 代码
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 的 Controller ,我使用此代码从我的app.js 页面重定向
app.all('/insertUser', attachDB, function(req, res, next) {
insertUser.run( req, res, next);
});
有人可以在 console.log 中帮助我吗?我收到了 {} .....
最佳答案
第一个测试是前端有问题。
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);
}
});
}
您应该在 Express 应用中设置 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);
},
});
关于javascript - php到node.js ajax发送没有给出响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32111099/