2015-09-05 171 views
0

之間的響應方法誤差嘿即時通訊目前使用快遞,佈局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是在默認

運行

回答

1

您使用衝突的res變量名。從app.post()http.request()檢查回調的變量名稱。

如果更改爲response相反,它可能工作,如果沒有其他的問題:

var req = http.request(options, function(response) { 
    response.on('data', function (chunk) { 
    ... 
+0

問題依然出現。它只是從res.setHeader chnageg到response.setHeader –

+0

試試這個:https://gist.github.com/endel/fa851d2cc5f5883a2055#file-stackoverflow-32418763-js-L19-L31 – Endel

+0

謝謝,作品:) 只是即使我渲染一個新的頁面,頁面也不會改變... –

相關問題