简体   繁体   English

node.js:发送后无法设置标头

[英]node.js:Can't set headers after they are sent

I am learning Node.js at the moment, and i am trying to create a shopping list application, and i am trying to implement a search route, which checks if the query matches the val, here is the code 我目前正在学习Node.js,并且尝试创建购物清单应用程序,并且尝试实现搜索路线,该路线检查查询是否匹配val,这是代码

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

//Array List 
let list = ['Fish', 'Lettuce', 'Chicken'];

//Set view engine to pug
app.set('view engine', 'pug');
//use bodyParser


app.get('/', function(request, response){
    response.render('list', {list});
});

app.get('/search', function(request, response){
   return list.map(function(val){
      if(request.query.search === val){
          return response.send('Yup you got ' + val);
        }
     response.send('Not found')
    });
});

app.get('/new-item', function(request, response){
    response.render('new');
});

app.post('/add-item', function(request, response){
   let add = response.send(request.body);
   list.push(add);
});

app.listen(port, function(){
    console.log('Listening on Port 3000');
});

Now the problem is with the /search route's if conditional, i know the reason i am getting the error is because i can't use the response.send twice, i am looking for a way to send either response, based on if the condition is met. 现在问题出在/search路由if有条件的if下,我知道我收到此错误的原因是因为我无法使用response.send两次,我正在根据情况确定是否要发送任一响应被满足。 Any help is appreciated Thanks 任何帮助表示赞赏,谢谢

Move response.send('Not found') outside of the loop. response.send('Not found')移出循环。 Also, you shouldn't use Array.map here, use Array#find instead: 另外,您不应在此处使用Array.map ,而应使用Array#find

app.get('/search', function(request, response) {
   let foundVal = list.find(function(val) {
     if (request.query.search === val) {
       return val;
     }
   });
   if (foundVal) {
     return response.send('Yup you got: ' + foundVal);
   }
   response.send('Not found');
});

Build your structure with callbacks. 使用回调构建您的结构。

app.get('/search', function(request, response){
    checkValue(list,request.query.search,function (result) {
        response.send({
            data : result
        });
    });

    function checkValue(list, value, callback) {
        var isHere = false;
        list.map(function(val){
            if(request.query.search === val){
                isHere = true;
            }
        });
        callback(isHere);
    }
});

In this piece of code: 在这段代码中:

app.get('/search', function(request, response){
   return list.map(function(val){
      if(request.query.search === val){
          return response.send('Yup you got ' + val);
        }
        response.send('Not found')
    });
});

You are doing response.send() inside your .map() callback which means you can easily call it more than once and the error you asked about indicates that you are calling it more than once. 您正在.map()回调内部执行response.send() ,这意味着您可以轻松地多次调用它,并且询问的错误表明您多次调用它。 Keep in mind that the return inside your .map() does not break out of the .map() . 请记住, .map()内部的return不会超出.map() It only returns from that iteration of the callback function and then the next iteration of the .map() continues right after you return . 它仅从回调函数的该迭代返回,然后.map()的下一个迭代将在您return后继续。

If you want to break out of the iteration, then switch to a regular for loop to do your iteration (which does not use a callback) and then your return will do what you want like this: 如果要中断迭代,请切换到常规的for循环进行迭代(不使用回调),然后您的return将执行您想要的操作:

app.get('/search', function(request, response){
    for (let val of list) {
        if (request.query.search === val){
            return response.send('Yup you got ' + val);
        }
    }
    response.send('Not found')
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM