node js服务器和客户端之间的响应方法错误

时间:2015-09-05 23:59:37

标签: javascript ajax node.js http express

嘿我目前使用node.js

在我的第一个真实网页上工作

我使用Express,ejs进行布局,将redis用作数据库。我试图从我的索引页面通过我的客户端发送ajax调用到我的服务器,在那里使用ajax调用并将最终的json传递回我的客户端,我尝试在下一个ejs页面上呈现它。

Ajax:

$(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 个答案:

答案 0 :(得分:1)

您正在使用冲突的res变量名称。检查来自app.post()http.request()的回调的变量名称。

如果您更改为response,则可能会有效,如果没有其他问题:

var req = http.request(options, function(response) {
  response.on('data', function (chunk) {
  ...
相关问题