Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

javascript - return res.status() doesn't seem to end my code from running?

If I hit an error I'd like it to return res.status an error to the front end, however I'm getting an error: Cannot set headers after they are sent to the client which I'm assuming means that it is going to the next res.status and the next one instead of actually returning for some reason.

betData.forEach(data => {
                    let storedAddress = `${data.address} ${data.city} ${data.state} ${data.zip}`;
                    let convertedAddress =`${addressData.data[0].delivery_line_1} ${addressData.data[0].last_line}`;
    
                    if(data.email.toLowerCase() === userInput.email.toLowerCase()){
                        return res.status(400).json({
                            message: `${userInput.email} has already been used this week.`
                        });
                    } else if (storedAddress === convertedAddress) {
                        return res.status(400).json({
                            message: `This address has already been used this week.`
                        });
                    } else {
                        const saveData = {
                            firstName: userInput.firstName,
                            lastName: userInput.lastName,
                            email: userInput.email,
                            address: addressData.data[0].delivery_line_1,
                            city: addressData.data[0].components.city_name,
                            state: addressData.data[0].components.state_abbreviation,
                            zip: addressData.data[0].components.zipcode,
                            favoriteTeam: userInput.favoriteTeam,
                            terms: userInput.terms,
                            agreeToEmail: userInput.agreeToEmail
                        }
                        saveGOTDBet(saveData).then(data => {
                            return res.status(200).json({
                                message: 'Bet successfully placed',
                            });
                        })
                    }
                });

As you can see I have multiple return res.status() calls, and multiple run because it doesn't actually end my code from running. Not sure what's going on here. Any help would be appreciated.

question from:https://stackoverflow.com/questions/65647541/return-res-status-doesnt-seem-to-end-my-code-from-running

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're looping in a forEach, which will run for each element. For a simpler example, try this in your Node REPL: [1,2,3].forEach(x => console.log(x) || x). Even though it returns, it's only returning and then continuing to the next iteration. You also have one res.send in the .then of a a Promise, which could be a further issue if that block gets hit. It looks like what you probably want to do is build up the response object while iterating over betData, and move your conditions and responses out of the iteration.

Here's an example of how this could work, though without knowing why you have more than one betData item to loop over I'm not sure if it will be perfect for your use case. Also the async/Promise saveGOTDBet could continue to be an issue.

let status = 200
let message = ''

betData.forEach(async (data) => {
  const storedAddress = `${data.address} ${data.city} ${data.state} ${data.zip}`
  const convertedAddress =`${addressData.data[0].delivery_line_1} ${addressData.data[0].last_line}`

  if (data.email.toLowerCase() === userInput.email.toLowerCase()) {
    status = 400
    message = message: `${userInput.email} has already been used this week.`
  } else if (storedAddress === convertedAddress) {
    status = 400
    message = `This address has already been used this week.`
  } else {
    const saveData = {
      firstName: userInput.firstName,
      lastName: userInput.lastName,
      email: userInput.email,
      address: addressData.data[0].delivery_line_1,
      city: addressData.data[0].components.city_name,
      state: addressData.data[0].components.state_abbreviation,
      zip: addressData.data[0].components.zipcode,
      favoriteTeam: userInput.favoriteTeam,
      terms: userInput.terms,
      agreeToEmail: userInput.agreeToEmail
    }

    await saveGOTDBet(saveData)
    status = 200
    message = 'Bet successfully placed',
  }
})

res.status(status).json({ message })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...