res sendFile 没有发送任何东西

问题描述

我目前正在尝试将 mailChimp API 合并到我的项目中,但负责发送成功代码的 resFile 代码不起作用。

代码

    async function run(){
        try {
            const res = await mailchimp.lists.addListMember(listId,{
                email_address: subscribingUser.emailAddress,status: "subscribed",merge_fields: {
                    NAME: subscribingUser.userName
                }
            });
            console.log(`Successfully added contact as an audience member. The contact's id is ${res.id}.`);
            console.log(res);
            //this res.sendFile does not send the file
            res.sendFile(__dirname + "/success.html");
        } catch(error) {
            //Code went straight to this and answered "error undefined"
            console.log(`Error ${error.status}.`);
            //This file was successfully sent following the "error undefined"
            res.sendFile(__dirname + "/failure.html");
        }
    }
    run();
});

我试过了:

1)重命名成功文件(不起作用)

2)交换成功和失败文件(不起作用)

结果都是一样的 预期结果:成功完成后将成功文件发送给客户端。已成功创建订阅用户 实际结果:尽管成功完成,但仍将失败文件发送给客户端,终端显示错误未定义”。已成功创建订阅用户

编辑 1(发布此帖子后 8 小时): 我通过改变

解决了这个问题
const res = await mailchimp.....

const response = await mailchimp...

整个工作代码片段粘贴在下面。但是,我还不知道它为什么起作用。我在下面的代码片段中有一些理论。如果有人能够阐明原因,如果您能这样做,我将不胜感激。感谢所有提供帮助的人!

///This is the res I am trying to call.
app.post("/",function(req,res){
    //The client's name and email
    const clientName = req.body.userName;
    const clientEmail = req.body.userEmail;
    //my unique list ID is here,so I censored it.
    const listId = "XXXXXXX";
    const subscribingUser = {
        emailAddress: clientEmail,userName: clientName
    }
    //Showing us the values of the variables in the object subscribingUser
    //Tells us what the user had inputted into the website.
    console.log(subscribingUser);
    async function run(){
        try {
            ///This was probably why it registered the res.SendFIle in the try 
            ///function as a function,as it overrode the res mentioned above at
            ///app.post.
            const response = await mailchimp.lists.addListMember(listId,merge_fields: {
                    NAME: subscribingUser.userName
                }
            });
            console.log(`Successfully added contact as an audience member. The contact's id is ${response.id}.`);
            res.sendFile(__dirname + "/success.html");
        } catch(error) {
            console.log(`Error ${error}.`);
            res.sendFile(__dirname + "/failure.html");
        }
    }
    run();
});

解决方法

试试这个:

res.sendFile('success.html',{root: __dirname })