Is there a way to resolve this issue? (An error occurred: TypeError - res.json is not a valid function)

When attempting to add an object to my MongoDB database

const response = await fetch("/api/contact", {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
        "Content-Type": "application/json",
    },
});

I encounter the error message [Something went wrong TypeError: res.json is not a function]

import React from "react";
import { NextResponse, NextRequest } from "next/server";
import wordModel from "../../../models/wordModel";
import mongoose from "mongoose";

export async function POST(req, res) {
    const MONGO_URI = process.env.MONGO_URI;
    try{
        await mongoose.connect(MONGO_URI)
        console.log("It's good");
        const word = await wordModel.create(req.body);
        res.json({ word }); 
    } catch(error) {
        console.log("Something went wrong", error);
        return new Response;
    }
}

Subsequently, a document with random numbers and letters appears in my database

Answer №1

For more information, check out: https://nextjs.org/docs/app/api-reference/functions/next-response#json

Do you think you should implement something similar to this?

async function handlePOSTRequest(req, res) {
  const MONGO_URI = process.env.MONGO_URI;
  
  try{
    await mongoose.connect(MONGO_URI)
    console.log("Everything is looking good");
    
    const data = await wordModel.create(req.body);
    
    return NextResponse.json({ someProp: data }, { status: 200 })
    
  } catch(error) {
    console.log("An error occurred", error);
    
    return NextResponse.json({ error: "An error occurred" }, { status: 500 })
  }
}

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

Issue with vue-cli3 eslint and compiler arising from conflicting vue/script-indent settings

Whenever my .eslint.js file includes this rule: "vue/script-indent": [ "error", 4, { "baseIndent": 1, "switchCase": 1, } ] and I save it, an error pops up: Error: Expected indentation of 32 spaces but only found 24 spaces ...

Exploring the meaning behind RxJS debounce principles

Referencing information found in this source: const debouncedInput = example.debounceTime(5); const subscribe = debouncedInput.subscribe(val => { console.log(`Debounced Input: ${val}`); }); When the first keyup event occurs, will the debouncedI ...

Guide on verifying the presence of an alert with nodejs webdriver (wd)

I am currently facing a challenge when writing a test where I need to verify the existence of an alert, check its text if it is present, and then accept it. Although I have researched on platforms like Stack Overflow for solutions such as checking for ale ...

The SWR library was called with an invalid hook

Attempting to make a delete request using the SWR library within a react hook. I understand that hooks cannot be called inside return(). How can I carry out a delete request using useSWR in my react hook project? Thank you. const page = () => { func ...

An analysis of Universal Angular.io and Prerender.io from the viewpoint of Googlebot

Currently, my website is set up with Angular 1.4.x and prerender.io, which delivers static cached pages to Googlebot. Googlebot visits each page twice - once by hitting the URL directly, and then again by appending ?_escaped_fragment_ to the URL to access ...

Is it possible to include a while loop for iteration inside a AJAX success function?

I'm currently working on dynamically creating an accordion and populating the content of each tab using AJAX. In my main HTML page, there is an empty div reserved for the accordion: <div id="accordion"></div> The desired outcome is to ha ...

Steps to include a HTML webpage within another page

I need assistance with a scenario involving two separate HTML pages on different servers. Merchant Form - Server A Payment Form - Server B Here's the desired scenario: The user completes all necessary fields on the Merchant Form and clicks submit. ...

Encountering an issue in react.js where pushing the URL with ID is not possible due to a missing dependency in the useEffect hook array

I am encountering an issue where I am unable to successfully push the id with history.push in my React application. Strangely, if I omit the id, everything works as expected. This problem is occurring while using react-router-dom version 5. useEffect(() =& ...

Image remains fluid within a static div without resizing

Any assistance would be greatly appreciated. I am currently facing an issue with a fixed div that is floating at the bottom of the screen, serving as ad space for the mobile version of a website. The problem arises when attempting to resize the browser win ...

Utilizing Ajax and Jquery to dynamically adjust CSS properties, dependent on data from a specific MySQL row

I've been working on a system to automatically update a Scene Selection page whenever a new number is added to the permission table in Mysql. The PHP for the login and retrieving the number from the members table is working fine. My issue now lies wi ...

"Enhance Your Website with Slider Swipe Effects using CSS3 and

After scouring the internet for various types of sliders, including swipe sliders, I am interested in creating a responsive swipe slider specifically for mobile phones. This would be a full page swipe slider where users can swipe left and right seamlessly. ...

The JSP page does not redirect after an Ajax post request has been made

When submitting a form with basic AJAX post, I am facing an issue where the redirection to the JSP does not occur upon success. Setting the redirect programmatically seems to create a new JSP instead of utilizing the existing one with POST data. After debu ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

What is the best way to create a transparent sticky header that blends with the background while still maintaining visibility over images and text?

On my web page, the background features a radial gradient but the content extends beyond the viewport, causing the center of the gradient to not align with the center of the screen, producing the desired effect. However, I'm facing an issue with a sti ...

What is the speed difference between calling functions from require's cache in Node.js and functions in the global scope?

Let's imagine a scenario where we have two files: external.js and main.js. // external.js //create a print function that is accessible globally module.exports.print = function(text) { console.log(text) } Now let's take a look at main.js: ...

Guide to creating a toggle button

Can someone help me create a button that toggles between displaying block and display none when clicked? I've been trying to use Classlist.toggle with JavaScript, but I'm not sure if I have the correct classes targeted. let showCart = documen ...

Ref cannot be assigned to function components. Trying to reference a ref in a function component will not work

Having trouble passing a ref in the MenuItem component while using react-beautiful-dnd. I tried creating a HOC with React.forwardRef but it didn't work. Any help in fixing this issue would be greatly appreciated. Error: https://i.stack.imgur.com/bLIN ...

Using Nextjs and Puppeteer for Web Scraping on Vercel Deployment

Currently, I am developing a web scraping tool using Next.js and Puppeteer. The project runs smoothly on my local machine; however, once deployed on Vercel, I encounter a 500 internal server error when attempting to utilize Puppeteer. Despite exploring var ...

Using jest.fn() to simulate fetch calls in React

Can anyone explain why I have to include fetch mock logic within my test in order for it to function properly? Let's take a look at a simple example: Component that uses fetch inside useEffect and updates state after receiving a response: // Test.js ...

Unleashing the power of JavaScript: Sharing arrays and data structures effortlessly

Currently, I am utilizing HTML & JavaScript on the client side and NodeJs for the server side of my project. Incorporated in my form are multiple radio buttons. When the user clicks on the submit button, my intention is to post the results to the server. ...