Hi there,
I have a Nuxt 3 server function that we want to use to upload images to our CMS (Dato).
The following code works successfully locally, but when it is deployed to Netlify the endpont returns a 502 Bad Gateway response:
error decoding lambda response: invalid status code returned from lambda: 0
This is the code in the API route. As mentioned, this works successfully locally but doesn’t work when the site is uploaded to Netlify.
import formidable from 'formidable';
import { buildClient } from '@datocms/cma-client-node';
export default defineEventHandler(async (event) => {
// Set up
const config = useRuntimeConfig(event);
const client = buildClient({ apiToken: config.datoPaeKey });
// Get the body of the request
let body;
const headers = getRequestHeaders(event);
if (headers['content-type']?.includes('multipart/form-data')) {
try {
body = await parseMultipartNodeRequest(event.node.req);
} catch (error) {
return { ok: false, error: error.message };
}
} else {
return { ok: false, error: 'Invalid content type' };
}
if (!body.file || !body.file.length > 0) {
return { ok: false, error: 'No file found' };
}
console.log('body', body);
const fileIds = [];
for (let file of body.file) {
try {
const upload = await client.uploads.createFromLocalFile({
// File object to upload
localPath: file.filepath,
filename: file.originalFilename,
tags: ['user-uploaded'],
// specify some additional metadata to the upload resource
});
console.log('dato', upload);
if (!!upload?.id) {
fileIds.push(upload.id);
}
} catch (error) {
return { ok: false, error: error.message };
}
}
return { ok: true, fileIds };
});
function parseMultipartNodeRequest(req) {
console.log('parseMultipartNodeRequest');
return new Promise((resolve, reject) => {
const form = formidable({ multiples: true });
form.parse(req, (error, fields, files) => {
if (error) {
console.error('error', error);
reject(error);
return;
}
resolve({ ...fields, ...files });
});
});
}
I’m not getting any errors in the Netlify function log so it’s very difficult to trouble shoot where it is failing. Any help on where to look to resolve this issue would be much appreciated.