Error: Unable to access data from an undefined variable (retrieving 'json')

Issue with Pushing Data into Mongo Database Using TypeScript and Next.js

Greetings, I am currently working on a project using TypeScript with Node/Next.js 13, the new app router, and Mongoose to push data into a MongoDB database. However, I am encountering an error that states: "TypeError: Cannot read properties of undefined (reading 'json').". Although the payload is visible in the browser's Network section, it is not being successfully passed to the database. As a newcomer to Next.js and TypeScript, I acknowledge that I may have overlooked something obvious, but I have exhausted numerous solutions without success. Any assistance would be greatly appreciated!

The objective is to insert data into the database upon creating a new product.

product/new/page.tsx

"use client"

import Plan from "@/app/components/Plan";
import axios from "axios";
import { useState } from "react";
...

src/app/api/products/page.ts

import { NextApiRequest, NextApiResponse } from "next";
import { NextResponse } from "next/server";
import { mongooseConnect } from "../../../../lib/mongoose";
import { Product } from "../../../../models/Product";
...

The console output when attempting to troubleshoot the 'res.json' response:

{ res: undefined } { req: { params: {}, searchParams: {} } }

models/Product.ts

import mongoose, { Schema } from "mongoose";
...

lib/mongoose.ts

import mongoose from "mongoose";
...

lib/mongodb.ts

// Implementation sourced from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
import { MongoClient } from "mongodb";
...

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "models/Product.js", "src/app/api/products/page.js", "src/app/api/products.js"],
  "exclude": ["node_modules"]
}

Answer №1

your API handle method is experiencing issues.

export default async function handle(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // always wrap async code in try/catch
  try {
    const { method } = req;
    await mongooseConnect();
    console.log({ res });
    console.log({ req });
    const { title, description, price } = req.body || {};
    // ensure required fields are passed
    if (!title || !description || !price){
      console.error("If you see this, it means you did not provide all required fields correctly.")
      // handle the situation accordingly
    }
    const productDoc = await Product.create({
      title,
      description,
      price,
    });
    const data = res.json(productDoc);
    return NextResponse.json(data);
  } catch (error) {
    console.error("Error in handler:", error);
  }
}

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

Decoding JSON arrays within a nested dictionary

I am utilizing a JSON API in my application to verify if a company utilizes electronic invoicing. The JSON data structure I am working with looks like this: { "ErrorStatus": null, "Result": { "CustomerList": [ { ...

Refresh client web pages with JSON data without using eval

I am currently working as a consultant on a web application that functions as a single page app. The main purpose of the app is to constantly fetch new json data in the background (approximately every minute) and then display it on the screen. Our clients ...

Having trouble navigating the maze of Express routing

app.js file // home route app.get("/home", async(req, res)=>{ let allCards = await Card.find({}); let skills = await Skill.find({}); res.render("index", {allCards, skills}); }) // add new skill route app.get("/home/newskill", (req, res)=& ...

Retrieving sibling JSON information using Handlebars: How to handle a situation where a single object lacks a parent index key, yet multiple items possess an index key

Encountered a fascinating yet challenging scenario while working with data from an API that highlights the limitations of using a templating language like Handlebars. (Helpers, Helpers everywhere!) Is there a elegant solution for handling the following si ...

Middleware in Next.js is preventing access to the "/" endpoint

I've been working on setting up a middleware for my Next.js 14 project. I'm facing an issue with configuring the middleware to recognize the "/" route. Despite multiple attempts, I still can't get the middleware to work properly for the "/" ...

Error encountered when accessing Spotify API. The requested action requires proper permissions which are currently missing. Issue arises when attempting to

I am attempting to use the spotify-web-api-node library to play a track on my application const playSong = async () => { // Verify access token with console.log(spotifyApi.getAccessToken()) setCurrentTrackId(track.track.id); setIsPlay ...

How can a .NET Core Rest API emit a stream to be consumed in Angular as an observable?

I'm interested in creating a dynamic page that continuously fetches data from the backend, allowing the data set to grow over time until the backend indicates completion (which may never happen). Similar to the concept discussed in this article, but u ...

When the start and end times are the same, the time picker is returning a null value

<input type="text" id="begin" class="form-control timepicker timepicker-no-seconds" name="start_event"> <input type="text" id="close" class="form-control timepicker timepicker-no-seconds" name="end_event"> The script for both is: $('#beg ...

justify-content property seems to be ineffective when used in Chakra UI

Currently in the process of developing a website using Next.js and Chakra-ui. I'm facing some issues with aligning the ButtonGroup to the end of the container. Despite trying to use justifyContent="space-between", it doesn't seem to be ...

Unusual behavior observed in Angular 2 when handling button click events

In my .ts file, there are two straightforward methods: editLocation(index) {} deleteLocation(index) { this.locations.splice(index, 1); } The corresponding HTML triggers these methods when buttons are clicked: <button (click)="editLocation(i)" ...

Error message: The class heritage events_1.EventEmitter is invalid and cannot be recognized

There seems to be a problem with the [email protected] npm dependency. I am attempting to incorporate mongodb into my Vue.js + Vite + Typescript application, but it crashes and fails to load due to an error originating from mongodb. It appears that th ...

The JSON list is not being properly flattened

I have a list displayed in a column format within a data frame. The variables change across the items, and the column affiliations may not always be present. I've been attempting to transform the list into either a flattened data frame or a list con ...

Python pymysql encountering a syntax error when trying to insert a JSON object

Encountered the following error when trying to insert data into a SQL database table using Python: pymysql.err.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the ...

What is the best way to structure and send messages over TCP in node.js?

Currently, I am working on a project that involves sending a JSON string to multiple TCP clients from a node.js TCP server. To successfully handle the incoming messages on the client end, I need to implement message framing. One approach I am considering ...

Retrieving information from BlobStorage using Service.ts and triggering the NgOnit function

Within the service.ts module, I am fetching data from Azure Blobstorage and attempting to read its contents. service.ts import { Injectable } from '@angular/core'; import { environment } from '../../environments/environment'; import { ...

Assign a variable to set the property of a class

Could something similar to this scenario be achievable? const dynamicPropName = "x"; class A { static propName = 1 // equivalent to static x = 1 } A[dynamicPropName] // will result in 1 or would it need to be accessed as (typeof A)[dynamicPropN ...

Is it possible to add to JSON formatting?

Here is the JSON object I have: new Ajax.Request(url, { method: 'post', contentType: "application/x-www-form-urlencoded", parameters: { "javax.faces.ViewState": encodedViewState, "client-id": options._clientId, ...

Guide on retrieving and presenting images in React from a Cloudinary URL stored in MongoDB

Recently, I started integrating Cloudinary into my application for uploading images. These images are stored in a MongoDB database as URL links. The upload process was successful, and this is how the database looks after saving: id:5f90315331dc1727bc869afe ...

Utilizing Javascript to Extract Data from Twitter Json Files

Can someone provide assistance with parsing JSON feed text retrieved from Twitter? I am looking to access and apply style tags to elements like the link, created date, and other information. Any tips on how I can achieve this task successfully would be g ...

Encountering a JSON parse error while utilizing the getJSON function

First time delving into coding with JavaScript and JSON, encountering an error message when using getJSON: parsererror SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data return window.JSON.parse( data ); Below is my code ...