gpt4 book ai didi

javascript - node.js:发送后无法设置 header

转载 作者:行者123 更新时间:2023-12-01 02:59:37 25 4
gpt4 key购买 nike

我现在正在学习 Node.js,我正在尝试创建一个购物 list 应用程序,并且我正在尝试实现一个搜索路由,该路由检查查询是否与 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');
});

现在问题出在 /search 路由的 if 条件上,我知道收到错误的原因是因为我无法使用 响应.send 两次,我正在寻找一种根据条件是否满足来发送任一响应的方法。任何帮助表示赞赏谢谢

最佳答案

response.send('Not find') 移到循环之外。另外,您不应该在此处使用 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');
});

关于javascript - node.js:发送后无法设置 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46521784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com