简体   繁体   中英

im getting 404 api not found

Im using mailgun to send email yet I am getting 404(not found) error. Here is my work

Client side

this.state= {
   message: "main message",
}

handeSendRequest(){
  await fetch('/api/eMail', {method:'post', headers: {'Content-type' : 'application/json' }}, body: JSON.stringify(this.state)){
}

}
render(){
  return(
    <Button onClick={this.handeSendRequest} > Send it </Button>
   )

 }

emailRouter.js

const mailgun = require('mailgun-js')(configuration);

router.post('/api/eMail', async (req,res) => {
    try {

        let message = req.body.message;
      sendEmail(message,function (err) {
                    if(err){
                        console.log(err);
                    }else{
                        console.log("Sent email");
                    }

                });

 res.status(200).json({
            success: true,
            msg: 'Success'
        });
    }
    catch(err) {
        res.status(400).json({
            success: false,
            msg: err
        });
    }
});


function mail(message, callback){

  const mail = `<p>{message}</p>`;

    var mail = mailcomposer({
        from: 'from@email.com',
        to: "to@email.com",
        subject: "subject",
        html: mail
    });
    mail.build(function(mailBuildError, message) {

        var dataToSend = {
            to: to@email.com,
            message: message.toString('ascii')
        };

        mailgun.messages().sendMime(dataToSend, function (sendError, body) {
            if (sendError) {
                console.log(sendError);
            }
            callback(sendError);

        });
    });
}

Server.js

const app = express();

const emailUtil = require('./emailRouter.js');

app.use('/api/eMail', emailUtil);

Not sure why but I'm getting these error http://localhost:3000/api/eMail 404 (Not Found) . Looks like the client side is right but the backend for some reason not getting the call. How can I modify my work so that the email can successfully be sent.

And what if you just register like this : app.use(emailUtil); cause, you register both the /api/eMail, in your server.js, and in your emailRouter.js

Then I think, express want you to request on /api/eMail/api/eMail

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM