fix:use basic auth to access listmonk

This commit is contained in:
Ryan Mwangi 2024-11-15 13:50:54 +03:00
parent 5e92b173d2
commit ce30c36587
1 changed files with 16 additions and 5 deletions

View File

@ -4,8 +4,16 @@ import fetch from 'node-fetch';
export async function submitToListmonk(req, res) { export async function submitToListmonk(req, res) {
const { name, email, message } = req.body; const { name, email, message } = req.body;
const listmonkUrl = process.env.LISTMONK_URL; const listmonkUrl = process.env.LISTMONK_URL;
const apiKey = process.env.API_KEY; const listmonkUsername = process.env.LISTMONK_USERNAME;
const listmonkPassword = process.env.LISTMONK_PASSWORD;
// Encode username and password as base64
const auth = Buffer.from(`${listmonkUsername}:${listmonkPassword}`).toString('base64');
console.log(`Sending request to Listmonk with URL: ${listmonkUrl}`);
const payload = { const payload = {
email, email,
@ -14,18 +22,21 @@ export async function submitToListmonk(req, res) {
fields: { message } fields: { message }
}; };
console.log('Sending request to Listmonk with payload:', payload);
try { try {
const response = await fetch(listmonkUrl, { const response = await fetch(listmonkUrl, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}` 'Authorization': `Basic ${auth}`
}, },
body: JSON.stringify(payload) body: JSON.stringify(payload)
}); })
if (!response.ok) { if (!response.ok) {
throw new Error(`Listmonk API error: ${response.statusText}`); const errorBody = await response.text(); // Get the response body as text
throw new Error(`Listmonk API error: ${response.statusText}. Response body: ${errorBody}`);
} }
const result = await response.json(); const result = await response.json();