I'm attempting to retrieve a JSON file from an S3 bucket. Here is the API route I'm using to fetch the json file:
const {GetObjectCommand, S3Client} = require("@aws-sdk/client-s3");
const client = new S3Client() // Add opts to S3 if needed
function getObject (Bucket, Key) {
return new Promise(async (resolve, reject) => {
const getObjectCommand = new GetObjectCommand({ Bucket, Key })
try {
const response = await client.send(getObjectCommand)
let responseDataChunks = []
response.Body.once('error', err => reject(err))
response.Body.on('data', chunk => responseDataChunks.push(chunk))
response.Body.once('end', () => resolve(responseDataChunks.join('')))
} catch (err) {
return reject(err)
}
})
}
export default async (req, res) => {
const records = await getObject('bucket', 'file.json')
res.statusCode = 200;
res.json(records)
};
Here is how I am fetching the data:
fetch('/api/getRecords').then(res => res.json()).then(data => {console.log(data)})
When checking the console, I encounter these errors:
GET https://www.example.com/api/getRecords 500
and
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
The strange thing is that this only occurs in my production environment. Everything works perfectly when I visit the api route in my development environment.
Upon inspecting the response from the api route in the production environment, it returns html instead of the json file from the S3 bucket it should be fetching.
<!DOCTYPE html>
<html>
... <!-- HTML content continues -->
Does anyone have any idea on how to resolve this issue?