2016-09-16 32 views
0

該代碼可以正常使用取消註釋行。 但是,當我激活else聲明我得到的每一次'未找到'即使有req.params.codedata.airports[i].code之間的匹配。使用node.js和express框架將請求參數與JSON對象進行匹配

var express = require('express'); 
 
var data = require('./data.json'); 
 
var app = express(); 
 

 
app.use(express.static('public')); 
 
app.set('view engine', 'jade'); 
 

 
app.get('/', function (req, res) { 
 
    res.render('index', { title: 'Startseite', message: 'index.html'}); 
 
}); 
 

 
app.get('/de-de/code/:code', function (req, res) { 
 
    for (var i in data.airports) { 
 
    if (req.params.code == data.airports[i].code) { 
 
     res.render('iata-code', data.airports[i]); 
 
/* } else { 
 
     res.send('not found'); */ 
 
    }; 
 
    }; 
 
}); 
 

 
app.listen(80, function() { 
 
    console.log('Example app is running!'); 
 
});

編輯: 我的代碼更改爲:

​​

即使我的頭,我收到之前發送的HTTP狀態碼404錯誤我的控制檯:Error: Can't set headers after they are sent.

EDIT2:

app.get('/de-de/code/:code', function (req, res) { 
 
    for (var i in data.airports) { 
 
    if (req.params.code === data.airports[i].code) { 
 
     res.writeHead(200, { "Content-Type": "text/html" }); 
 
     res.render('iata-code', data.airports[i]); 
 
    } else { 
 
     res.writeHead(404, { "Content-Type": "text/html" }); 
 
     res.write('Something failed!'); 
 
     res.end(); 
 
    }; 
 
    }; 
 
});

EDIT3:我建立了一個替代方法。但是這也不起作用。我是node.js的新手,但我仍然沒有找到解決方案。

var express = require('express'); 
 
var data = require('./data.json'); 
 
var airports = data.airports; 
 
var app = express(); 
 

 
function filterData (reqCode) { 
 
    var result = {}; 
 
    for (var i in airports) { 
 
    console.log('-----'); 
 
    console.log(i + ': ' + reqCode + ' <--> ' + airports[i].code); 
 
    console.log('-----'); 
 
    if (airports[i].code === reqCode) { 
 
     result = airports[i]; 
 
    } else { 
 
     result = {}; 
 
    }; 
 
    }; 
 
    return result; 
 
    console.log(result); 
 
}; 
 

 
app.get('/de-de/:code', function (req, res, next) { 
 
    var reqCode = req.params.code; 
 
    if (filterData(reqCode) === {}) next('route'); 
 
    else next(); 
 
}, function (req, res, next) { 
 
    res.write('200'); 
 
    res.end(); 
 
}); 
 

 
app.get('/de-de/:code', function (req, res, next) { 
 
    res.write('404'); 
 
    res.end(); 
 
}); 
 

 
app.listen(80, function() { 
 
    console.log('Example app is running! Cancel Server with CTRL + C'); 
 
});

回答

-1

elsefor loop內,所以每當req.params.code == data.airports[0].code不返回true(第一道),它會返回not found,而不是通過一個候選下去。

-1

您正在發送response不止一個這就是爲什麼你得到這個問題。

Instead of res.send() you should use res.write() to send multiple responses.


res.send() sends entire HTTP response to the client includes headers and content even it ends the response . And after that, you can't send anything.

注: 完成loop後,你終於可以調用res.send(),如果它需要你。

+0

這也是行不通的。請參閱我的原始帖子中的** Edit2 **。 –

+0

你有什麼錯誤? – abdulbarik

+0

'錯誤:發送後無法設置標題.';( –