节点JS服务器和客户端
问题描述:
之间的响应方法误差嘿即时通讯目前使用快递,布局EJS和Redis的数据库使用Node.js的节点JS服务器和客户端
IM在我第一次真正的网页的工作。我试图从我的索引页面通过我的客户端发送ajax调用到我的服务器,在那里使用ajax-call并将最终的json传回给我的客户端,我尝试在下一个ejs页面上呈现它。
阿贾克斯:
$(function(){
$(".search").click(function() {
$.ajax({
method: "POST",
url: "/search",
cache: false,
data: {ort: "hierundda", activity: "Wandern", datum: "01.09.2015"},
dataType: "json",
success: function(data){
alert('Success!')
}
, error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err)
}
});
});
});
我的服务器路线:
rest.post("/search", jsonParser, function(req, res){
/*some database action with redis */
res.json(dataJson);
});
});
我的客户路线:
app.post('/search', jsonParser, function(req,res){
var test = JSON.stringify(req.body);
fs.readFile('./filterergebnis.ejs', {encoding: 'utf-8'}, function(err, filestring){
if(err){
throw err;
}
else{
var options = {
host: 'localhost',
port: 3000,
path: '/search',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': test.length
}
}
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
var userdata = JSON.parse(chunk);
console.log(userdata);
var html = ejs.render(filestring, userdata);
//here does the error appear...
res.setHeader('content-type', 'text/html');
res.writeHead(200);
res.write(html);
res.end();
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(test);
req.end();
}
});
});
这就好比错误的外观: http://www.pic-upload.de/view-28225954/stack.png.html
index.ejs是在默认
运行
答
您使用冲突的res
变量名。从app.post()
和http.request()
检查回调的变量名称。
如果更改为response
相反,它可能工作,如果没有其他的问题:
var req = http.request(options, function(response) {
response.on('data', function (chunk) {
...
问题依然出现。它只是从res.setHeader chnageg到response.setHeader –
试试这个:https://gist.github.com/endel/fa851d2cc5f5883a2055#file-stackoverflow-32418763-js-L19-L31 – Endel
谢谢,作品:) 只是即使我渲染一个新的页面,页面也不会改变... –