Error encountered when attempting to retrieve data from an API route using s3, resulting in an uncaught promise with the message "SyntaxError: Unexpected token < in JSON at position 0

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?

Answer №1

In my production environment, I encountered a problem with my access keys which resulted in one of my lambdas experiencing a permission denied error. Fortunately, after addressing this issue, the problem was successfully resolved. Special thanks to @Ermiya Eskandary for their invaluable assistance.

Answer №2

Always ensure that you connect to the production server and not the development server.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the shine: implementing reflection in THREE.js

Is there a way to achieve a material that reflects other shapes from the scene? I attempted to use the reflectivity property but had no success in seeing any reflection. I found an example demonstrating this effect It seems like non-standard materials we ...

Is there a way to transfer the content of a div into a fresh window while retaining its original formatting

Here is a way to copy a new page: var yourDOCTYPE = "<!DOCTYPE html..."; // the doctype declaration var printPreview = window.open('about:blank', 'print_preview'); var printDocument = printPreview.document; printDocument.open(); pri ...

Unable to fetch data using getJSON method

objecten.js var objectData = [ { image: 'gallery/objecten/bear.jpg', thumb: 'gallery/objecten/bear.jpg', title: 'my first image', description: 'Lorem ipsum caption&apos ...

Revoke the prior invocation of the Google Maps geocoding function

While working on implementing an autocomplete with JavaScript and the Google Maps geocode method (using the keyup event on input), I have encountered a problem where I sometimes receive the results of the previous search instead of the current one. I am l ...

Reorganize Material UI Grid Items with varying lengths

I'm currently working with a Material UI grid system that appears as shown below: <> <Typography gutterBottom variant='h6'> Add New User{' '} </Typography> <Grid container spacing={3} ...

Exploring the capabilities of referencing MongoDB documents with the populate method in Node.js

I have been working on referencing in Node.js using the populate method, but I am unsure about how exactly it works. In my code, I am creating a reference to the user collection from my child collection. I have two collections - one for children and anothe ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

One way to enhance user experience is by passing parameters dynamically from the database when an element is clicked. This allows for the retrieval of

Earlier, I tried to post a question but couldn't get it working due to incorrect code. As the title suggests, my objective is to retrieve data from a database and display it in a div. The idea is that when this data is clicked, it should be passed to ...

Creating a dropdown menu in Vue 3: A step-by-step guide

I've scoured the entire internet, but I still can't seem to resolve this issue. When using the code below, I keep getting an error message that says 'Uncaught ReferenceError: VueSelect is not defined.' Can you help me figure out what&ap ...

Modifying the color of an empty string is not feasible in Javascript

Is it possible to change the color of FirstName only when there is text input? Currently, it turns green when there's text, but I want it to turn red when it's empty. How can this be achieved? $(document).on("click", '.btn-info.mailCo ...

Does Vuex dispatch from within a component include a particular type of behavior known as a "promise"?

Currently, I am diving into vuex and facing an issue. During the created() lifecycle hook, my goal is to fetch data from an API. Once this action is complete, I need to call a getter from the component and assign the retrieved cards to the component's ...

TRPC: JSON response from createNextApiHandler experiences disruption

Problem Encountering Unexpected end of JSON input or Unterminated string in JSON at position errors with some queries and mutations This issue arose after a rebuild following an unrelated update. The code functions correctly locally but not on the hosting ...

Safari's anchor links tend to leap higher than necessary

One of the anchor links on my website is behaving strangely in Safari, both on iPhone and MacOS. Instead of scrolling to the correct position of the anchored div, it scrolls to a random location around 400-500px higher than it should be. All other anchor l ...

Retrieve the origin of the copied text

While working on a Vue application, I'm curious to know if it's possible to access the source of pasted text. For example, whether the pasted text originated from your own application, Word, or Notepad? I attempted the code below but was unable ...

Implementing Event Listeners in Vue 3.0: A Guide to Attaching to the Parent Element

How can I attach an addEventListener to the parent element in Vue 3.x? I discovered that you can access the parent by using this code: import { getCurrentInstance, onMounted } from 'vue' onMounted(() => { console.log(getCurrentInstance() ...

Using NPM in conjunction with a PHP/STATIC web site directory structure: A comprehensive guide

My PHP website has a file structure like this: / css/ js/ index.php When I run the following commands: npm init npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb8984849f989f998a9babdfc5dd">[email p ...

Recalling the layout following the user's computer restart

I am creating a simple online editing tool (similar to Microsoft Outline) for coursework and I would like the outline details to be saved even if the user restarts the system. How can I achieve this? <html> <head> <title>Editor</ ...

Encountering a difficulty in sending data to the server through ajax with Cordova

I am currently working on a Phonegap Cordova project and I'm trying to send data to the server using AJAX but I'm encountering an error. Here is an example of my code: $(document).ready(function() { $('#frm').submit(function() ...

Timeout for jQuery animations

My jQuery animation script is causing an issue where it does not finish the animation before returning to the parent function. Specifically, the JavaScript code changes a background color, calls the animate function, the animation starts but doesn't c ...

The criteria set by jQuery are met

I have developed my own custom form validation for two inputs: one for a phone number and the other for an email address. Additionally, I have integrated two forms on a single page. Here is a snippet of my code: var email, phone; if (email address passe ...