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

node js error on response methods between server and client

本文关键字:响应 方法 错误 之间 客户端 服务器      更新时间:2023-09-26

嘿,我目前正在使用node.js制作我的第一个真正的网页

我使用Express, ejs布局和redis作为数据库。我试图通过我的客户端发送一个ajax调用从我的索引页到我的服务器,使用ajax调用那里,并通过最后的json返回到我的客户端,我尝试在下一个js页面上渲染它。

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);
    });
});

My client route:

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

索引。Ejs在默认情况下运行

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

如果你改为response,它可能会工作,如果没有其他问题:

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