为什么可以使用node.js重定向到我的故障页面?

发布于 2025-02-08 08:40:03 字数 556 浏览 2 评论 0原文

我正在使用MailChimp API处理我的新闻通讯项目,它有效,但是如果状态代码不是200个,我无法重定向到故障页面,浏览器表示Localhost拒绝连接成功页面重定向非常有效。 这是我的代码:

app.post("/", async(req, res, next)=>{
  const {fName, lName, email} = req.body.user;
  const response = await mailchimp.lists.addListMember("List_ID", {
    email_address: email,
    status: "subscribed",
    merge_fields:{
      FNAME: fName,
      LNAME: lName,
    },
  });
  if(res.statusCode === 200){
    res.sendFile(__dirname + "/success.html");
  }
  else{
    res.sendFile(__dirname + "/failure.html");
  }

});

I am working on my newsletter project using Mailchimp API, it works but I can't redirect to a failure page if the status code is not 200, the browser says localhost refused to connect meanwhile success page redirection works great.
here's my code:

app.post("/", async(req, res, next)=>{
  const {fName, lName, email} = req.body.user;
  const response = await mailchimp.lists.addListMember("List_ID", {
    email_address: email,
    status: "subscribed",
    merge_fields:{
      FNAME: fName,
      LNAME: lName,
    },
  });
  if(res.statusCode === 200){
    res.sendFile(__dirname + "/success.html");
  }
  else{
    res.sendFile(__dirname + "/failure.html");
  }

});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一曲爱恨情仇 2025-02-15 08:40:03

首先,首先使用async express很棘手,如果您的async函数函数中的任何内容都不会通知会导致会导致的内容一个错误:

local主机拒绝连接

一个快速而肮脏的解决方案将是将async函数的整个身体扭曲成try .. catch block。但这很繁琐,您可能仍然会错过某些副条件。

因此,相反,您需要为可以这样看的包装器创建一个包装器:
(对于明确的异步包装器,可能有更好的实现)

function asyncExpressWrapper(fn) {
   // return the wrapping middelware be used.
   return async (req, res, next) => {
      try {
         // call the actual middelware you passed
         await fn(req, res, next);
      } catch (err) {
         // will catch any error thrown in fn
         next(err)
      }
   }
}

并以这种方式使用它:

app.post("/", asyncExpressWrapper(async(req, res, next) => {
  const {
    fName,
    lName,
    email
  } = req.body.user;

  const response = await mailchimp.lists.addListMember("List_ID", {
    email_address: email,
    status: "subscribed",
    merge_fields: {
      FNAME: fName,
      LNAME: lName,
    },
  });

  if (response.statusCode === 200) {
    res.sendFile(__dirname + "/success.html");
  } else {
    res.sendFile(__dirname + "/failure.html");
  }
}));

现在将解决localhost拒绝连接问题,而Express会告诉您您未处理哪些错误。

除此之外它必须是响应。STATUSCODE=== 200

现在,您的__ dirname +“/failure.html”可能仍未显示,因为mailchimp.lists.addlistmember可能会在错误情况中拒绝的承诺。因此,您还需要尝试...中间件中的catch

app.post("/", asyncExpressWrapper(async(req, res, next) => {
  const {
    fName,
    lName,
    email
  } = req.body.user;
  
  try {
    const response = await mailchimp.lists.addListMember("List_ID", {
      email_address: email,
      status: "subscribed",
      merge_fields: {
        FNAME: fName,
        LNAME: lName,
      },
    });

    // you probably don't need that if-else at all and only emit 
    // success here, but I don't know mailchimp.lists.addListMember 
    // so that's up to you to figure out. 
    if (response.statusCode === 200) {
      res.sendFile(__dirname + "/success.html");
    } else {
      res.sendFile(__dirname + "/failure.html");
    }
  } catch(err) {
    res.sendFile(__dirname + "/failure.html");
  }
}));

Express Documentation具有

const wrap = fn => (...args) => fn(...args).catch(args[2])

​偶然不会回报承诺。

First of all using async with express is tricky, if anything in your async function throws express won't get notified about that which would result in an error like:

localhost refused to connect

A quick and dirty solution would be to warp your whole body of the async function into a try .. catch block. But that's tedious and you might still miss some side conditions.

So instead you would want to create a wrapper for that which could look that way:
(There are probably better implementations for an express async wrapper)

function asyncExpressWrapper(fn) {
   // return the wrapping middelware be used.
   return async (req, res, next) => {
      try {
         // call the actual middelware you passed
         await fn(req, res, next);
      } catch (err) {
         // will catch any error thrown in fn
         next(err)
      }
   }
}

And use it that way:

app.post("/", asyncExpressWrapper(async(req, res, next) => {
  const {
    fName,
    lName,
    email
  } = req.body.user;

  const response = await mailchimp.lists.addListMember("List_ID", {
    email_address: email,
    status: "subscribed",
    merge_fields: {
      FNAME: fName,
      LNAME: lName,
    },
  });

  if (response.statusCode === 200) {
    res.sendFile(__dirname + "/success.html");
  } else {
    res.sendFile(__dirname + "/failure.html");
  }
}));

Now that will solve the localhost refused to connect problem, and express will tell you which error you didn't handle.

Besides that your res.statusCode === 200 will check the express response statusCode which at that point is always true, if response has a statusCode it has to be response.statusCode === 200.

Now your __dirname + "/failure.html" likely still is not shown, as the Promise returned by mailchimp.lists.addListMember likely rejects in the error case. So you needd also a try ... catch in your middleware:

app.post("/", asyncExpressWrapper(async(req, res, next) => {
  const {
    fName,
    lName,
    email
  } = req.body.user;
  
  try {
    const response = await mailchimp.lists.addListMember("List_ID", {
      email_address: email,
      status: "subscribed",
      merge_fields: {
        FNAME: fName,
        LNAME: lName,
      },
    });

    // you probably don't need that if-else at all and only emit 
    // success here, but I don't know mailchimp.lists.addListMember 
    // so that's up to you to figure out. 
    if (response.statusCode === 200) {
      res.sendFile(__dirname + "/success.html");
    } else {
      res.sendFile(__dirname + "/failure.html");
    }
  } catch(err) {
    res.sendFile(__dirname + "/failure.html");
  }
}));

The Express documentation has a section about Promises suggesting this as a wrapper:

const wrap = fn => (...args) => fn(...args).catch(args[2])

The one I suggested also works if you pass a none async function to it from which you accidentally don't return a Promise.

吃不饱 2025-02-15 08:40:03

也许您可以使用“ try..catch”来捕获意外错误。
见下文。

try {
   if(res.statusCode === 200){
      res.sendFile(__dirname + "/success.html");
   }
   else{
     res.sendFile(__dirname + "/failure.html");
   }
} catch (err) {
   res.sendFile(__dirname + "/failure.html");
}

Maybe you can use "try..catch" to catch unexpected error.
See below.

try {
   if(res.statusCode === 200){
      res.sendFile(__dirname + "/success.html");
   }
   else{
     res.sendFile(__dirname + "/failure.html");
   }
} catch (err) {
   res.sendFile(__dirname + "/failure.html");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文