Encountering an 'Unexpected token u in JSON at position 0' error while utilizing the scan function in Amazon

I'm currently working on a Lambda function that is connected to an API. While most of the routes are functioning properly, I'm encountering an issue with the GET /items route which is supposed to retrieve all items from a DynamoDB table. Unfortunately, I keep getting the error message:

"Unexpected token u in JSON at position 0"

I've been following a tutorial outlined in the AWS Developer Guide:

https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-dynamo-db.html#http-api-dynamo-db-create-table

The tutorial suggests using the scan method to fetch all items from the table. However, when I implement this, it doesn't seem to work as expected:

const AWS = require("aws-sdk");

const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async(event, context) => {
  let body;
  let statusCode = 200;
  const headers = {
    "Content-Type": "application/json"
  };

  try {
    let requestJSON = JSON.parse(event.body);
    switch (event.routeKey) {
      case "GET /items":
        body = await dynamo.scan({
            TableName: "users"
          })
          .promise();
        break;
      case "PUT /signIn":
        await dynamo
          .update({
            TableName: "users",
            Key: {
              UserId: requestJSON.UserId
            },
            UpdateExpression: "set SignedInAt = :a, IsSignedIn = :b, SignedOutAt = :c",
            ExpressionAttributeValues: {
              ":a": new Date().toLocaleTimeString(),
              ":b": true,
              ":c": ""
            }
          })
          .promise();
        body = `User ${requestJSON.UserId} has been signed in.`;
        break;
      case "PUT /signOut":
        await dynamo
          .update({
            TableName: "users",
            Key: {
              UserId: requestJSON.UserId
            },
            UpdateExpression: "set SignedOutAt = :a, IsSignedIn = :b",
            ExpressionAttributeValues: {
              ":a": new Date().toLocaleTimeString(),
              ":b": false,
            }
          })
          .promise();
        body = `User ${requestJSON.UserId} has been signed out.`;
        break;
      default:
        throw new Error(`Unsupported route: "${event.routeKey}"`);
    }
  }
  catch (err) {
    statusCode = 400;
    body = err.message;
  }
  finally {
    body = JSON.stringify(body);
  }

  return {
    statusCode,
    body,
    headers
  };
};

Here's a link to the logs for more information:

https://i.sstatic.net/3BMV1.png

Answer №1

While attempting to process a request with an empty body via GET, I encountered some issues.

To resolve this, I have modified the code to only parse the body in PUT requests:

const AWS = require("aws-sdk");

const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async(event, context) => {
  let body;
  let requestJSON;
  let statusCode = 200;
  const headers = {
    "Content-Type": "application/json"
  };

  try {
    console.log(event.body);

    switch (event.routeKey) {
      case "GET /items":
        body = await dynamo.scan({
            TableName: "users"
          })
          .promise();
        break;
      case "PUT /signIn":
        requestJSON = JSON.parse(event.body);
        await dynamo
          .update({
            TableName: "users",
            Key: {UserId: requestJSON.UserId},
            UpdateExpression: "set SignedInAt = :a, IsSignedIn = :b, SignedOutAt = :c",
            ExpressionAttributeValues: {
              ":a": new Date().toLocaleTimeString(),
              ":b": true,
              ":c": ""
            }
          })
          .promise();
        body = `User ${requestJSON.UserId} has been signed in.`;
        break;
      case "PUT /signOut":
        requestJSON = JSON.parse(event.body);
        await dynamo
          .update({
            TableName: "users",
            Key: {UserId: requestJSON.UserId},
            UpdateExpression: "set SignedOutAt = :a, IsSignedIn = :b",
            ExpressionAttributeValues: {
              ":a": new Date().toLocaleTimeString(),
              ":b": false,
            }
          })
          .promise();
        body = `User ${requestJSON.UserId} has been signed out.`;
        break;
      default:
        throw new Error(`Unsupported route: "${event.routeKey}"`);
    }
  }
  catch (err) {
    statusCode = 400;
    body = err.message;
  }
  finally {
    console.log(event.body);
    body = JSON.stringify(body);
  }

  return {
    statusCode,
    body,
    headers
  };
};

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

Ways to specify an unused parameter within a function

As I work on my code, I encounter the need to separate the key and value from a request params object in order to validate the value using ObjectID. To achieve this, I decided to iterate over an array of entries and destructure the key and value for testin ...

Building a family tree with JavaScript's Document Object Model

My goal is to use jQuery to construct the following DOM setup: <li> <label> user <input type=radio> </label> </li> Below is the jQuery code I am trying to use. $('<input>') .attr({type:'radio&ap ...

Save the current date in the browser's localStorage

With jQuery Mobile 1.3, I successfully gathered and displayed values from input fields using localStorage through this function: <script type="text/javascript"> function datosCliente (info) { localStorage.setItem(info.name, info.valu ...

How to disable React Native yellow warnings in console using npm

Is there a way to get rid of those pesky yellow warnings flooding my npm console? It's becoming impossible to spot my own console.log messages amidst all the warning clutter. https://i.stack.imgur.com/JAMEa.jpg I've already attempted the follow ...

Exploring the contrasting outcomes between a request post and an axios post

After using request and wrapping it with a promise, I realized that I could write cleaner code by switching to axios. However, I encountered an internal server error (Request failed with status code 401) and since I don't have access to the backend co ...

VueD3tree successfully fetches data, however, it is not being displayed on the screen

Just started delving into Vue and VueD3tree. Attempting to display a tree using the vued3tree library with data pulled from an API. Strangely enough, when trying with static data, the tree displays perfectly fine. However, when fetching data dynamically, a ...

Having trouble getting Javascript to reveal hidden elements based on their class

I am having some trouble making specific fields in a form appear based on the selection made from a dropdown menu. Below is a simplified snippet of my code, which should change the display from 'none' to 'block'. Can you help me figure ...

Make an AJAX GET call to an ASP.NET Web API endpoint

Here is the ajax script I am using: $.ajax({ dataType: 'json', url: url, data: tuDispId, type: "GET", success: function (data) { bindData(data); $("#ale ...

What impact does reselect have on the visual presentation of components?

I'm struggling to grasp how reselect can decrease a component's rendering. Let me illustrate an example without reselect: const getListOfSomething = (state) => ( state.first.list[state.second.activeRecord] ); const mapStateToProps = (state ...

Is it appropriate to refer to a single page application as a web 3.0 application?

As time progresses, we are witnessing the rise of more and more single page applications or frameworks such as new twitter and Sammy. It appears to be a significant advancement where we move away from generating code on the server side, with servers actin ...

Various filters have been utilized on an array of objects

Within one of my Vue components, the code structure is as follows: <li class="comment" v-for="comment in comments"> ... </li> Accompanied by a computed method: computed: { comments() { // Here lies the logic for filtering comment ...

When querying parameters within a URL, you may encounter JavaScript (Node) errors

My current setup involves using Firebase Cloud Functions, but I have run into an issue. Whenever a parameter with a # symbol is received, it does not get recognized. For instance: http://example.net?id=123#456. When I check the logged id, only 123 is disp ...

Google Maps is experiencing difficulties maintaining its longitude and latitude coordinates within the Bootstrap tabbed user interface

I implemented ACF's Google Map to display a map on my webpage. I followed the instructions closely and made some minor modifications to the map js for styling purposes. One key change I had to make was in this section to ensure the map loads correctly ...

A common inquiry regarding Vue: How to effectively incorporate fullpage.js wrapper with additional functionalities

Having recently delved into Vue, I am currently tackling a project that involves the Fullpage.js Vue wrapper. While I have successfully implemented the Fullpage functionality, integrating additional features like an animation-on-scroll function has proven ...

Tips for transferring the output of a JavaScript async function to a Python variable

var = driver.execute_script("setTimeout(function(){ return [1,2,3]; }, 1000);") Utilizing the Selenium method execute_script, I am attempting to extract data from a website using javascript and assign it to a python variable var. The challenge a ...

Unable to properly execute Fetch Delete Request

When using the Fetch API, I am sending this request: const target = e.currentTarget; fetch(target.href, { method: 'delete', }) .then(res => console.log(22)) .catch(err => console.log(err)); In addition, here is the middleware that manag ...

Is it possible to identify a click that is being held without any movement?

Check out the code snippet below: doc.on('mousedown', '.qandacontent', function() { timeout_id = setTimeout(menu_toggle.bind(this), 1000); }).bind('mouseup mouseleave', function() { clearTimeout(timeout_id); }); If y ...

Switch Between Different Background Colors for Table Rows With Each Click

This script changes colors when a row in a specific column is clicked: $(document).ready(function(){ $("#rowClick").children("tbody").children("tr").children("td").click(function(){ $(this.parentNode).toggleClass("enroute"); }); }); CSS: .placed{ b ...

Handling an Express server that receives a request with no data

I'm struggling with a problem where I am unable to retrieve a basic JSON object. When I log it to the console, all I see is {}. Let me showcase the server code below: const express = require("express"); const app = express(); app.listen(3000); app.us ...

When URL string parameters are sent to an MVC controller action, they are received as null values

Are You Using a Controller? public class MyController : Controller { [HttpGet] public ActionResult MyAction(int iMode, string strSearch) { return View(); } } Within my view, I have a specific div with the id of "center" I am runn ...