为什么可以使用node.js重定向到我的故障页面?
我正在使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,首先使用
async
express
很棘手,如果您的async
函数函数中的任何内容都不会通知会导致会导致的内容一个错误:一个快速而肮脏的解决方案将是将
async
函数的整个身体扭曲成try .. catch
block。但这很繁琐,您可能仍然会错过某些副条件。因此,相反,您需要为可以这样看的包装器创建一个包装器:
(对于明确的异步包装器,可能有更好的实现)
并以这种方式使用它:
现在将解决
localhost拒绝连接
问题,而Express会告诉您您未处理哪些错误。除此之外它必须是
响应。STATUSCODE=== 200
。现在,您的
__ dirname +“/failure.html”
可能仍未显示,因为mailchimp.lists.addlistmember
可能会在错误情况中拒绝的承诺。因此,您还需要尝试...中间件中的catch
:Express Documentation具有
偶然不会回报承诺。
First of all using
async
withexpress
is tricky, if anything in yourasync
function throws express won't get notified about that which would result in an error like:A quick and dirty solution would be to warp your whole body of the
async
function into atry .. 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)
And use it that way:
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, ifresponse
has astatusCode
it has to beresponse.statusCode === 200
.Now your
__dirname + "/failure.html"
likely still is not shown, as the Promise returned bymailchimp.lists.addListMember
likely rejects in the error case. So you needd also atry ... catch
in your middleware:The Express documentation has a section about Promises suggesting this as a wrapper:
The one I suggested also works if you pass a none
async
function to it from which you accidentally don't return a Promise.也许您可以使用“ try..catch”来捕获意外错误。
见下文。
Maybe you can use "try..catch" to catch unexpected error.
See below.