如何在Node.js路由集成Mailjet发送API?401错误排查求助
Hey there, let's work through this 401 unauthorized error with Mailjet—this is almost always related to authentication or setup issues, so let's break down the fixes step by step:
1. Verify Mailjet API Key Configuration (Most Likely Culprit)
A 401 error usually means Mailjet doesn't recognize your credentials. Double-check these details:
- Make sure you've initialized the Mailjet client correctly with your public and private API keys. Your code should have something like this at the top:
const mailjet = require('node-mailjet').connect( process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE ); - Confirm the keys match exactly what's in your Mailjet dashboard—no extra spaces, typos, or missing characters. Remember: the private key should stay secure (never hardcode it in your repo; use environment variables).
2. Check Template Permissions and ID
Even if your keys are correct, a misconfigured template can cause issues:
- Ensure the
TemplateIDyou're using is valid and belongs to your Mailjet account. Double-check the number in your dashboard's transactional templates section. - Make sure the template is active—some templates require manual activation or approval before they can be used.
3. Fix Asynchronous Logic in Your Route
Your current POST route has a critical async flow issue that doesn't cause the 401, but will break your workflow once the auth is fixed:
- You're calling
contactModel.find({ _id: req.body._id })outside thenewContact.save()callback.req.body._iddoesn't exist here (the new contact's ID is only generated after saving), so this query will return nothing. - You should trigger the Mailjet request after the contact is successfully saved, and use the saved contact data instead of re-querying. Here's a revised version of your POST route:
router.post('/contact', function(req, res, next) { var newContact = new contactModel({ contactName: req.body.contactName, contactEmail: req.body.contactEmail, contactPhone: req.body.contactPhone, contactMessage: req.body.contactMessage, contactNews: req.body.contactNews }); newContact.save(function(error, savedContact) { if (error) { console.error('Failed to save contact:', error); return next(error); } // Send email ONLY after contact is saved const request = mailjet .post("send", {'version': 'v3.1'}) .request({ "Messages":[ { "From": { "Email": "xxxx@hotmail.fr", "Name": "xx" }, "To": [ { "Email": req.body.contactEmail, "Name": req.body.contactName } ], "TemplateID": xxxx, // Replace with your valid template ID "TemplateLanguage": true, "Subject": "xxx", "Variables": {} } ] }); request .then((result) => { console.log('Mailjet response:', result.body); // Fetch all contacts and render index after successful email send mongoose.model('contacts').find(function(err, contacts) { if (err) return next(err); req.session.contact = contacts; res.render('index', {contacts, isLoggedIn}); }); }) .catch((err) => { console.error('Mailjet error:', err.statusCode, err.message); next(err); }); }); });
4. Validate Your Sender Email
Mailjet requires sender emails to be verified to prevent spam. Make sure:
- The email
xxxx@hotmail.fris verified in your Mailjet account (either via single email verification or domain verification). Unverified senders can cause authorization or delivery failures.
5. Confirm SDK and API Version Compatibility
Ensure you're using the latest version of the Mailjet Node.js SDK. Outdated versions might have compatibility issues with the v3.1 API endpoint. You can update it via npm:
npm update node-mailjet
Start with checking your API keys first—that's the most common fix for 401s with Mailjet. Once that's sorted, adjust your async logic to keep your workflow consistent.
内容的提问来源于stack exchange,提问作者Blerni2.0

