Encountering JSON parsing errors while using fetch() POST requests in Express

Currently, I am experimenting with HTTP requests and my main focus is on sending a POST request. The data for this request is coming from an input field and I am using fetch() to send it to a URL on my local host which is set up with express. My goal is to receive the response back and display it on my HTML document.

However, I've encountered a puzzling issue wherein response.json() always returns undefined no matter what I do.

Here's the frontend script I'm working with:

const url = "/result";

const inputField = document.querySelector("#write");
const submitButton = document.querySelector("#submit");
const responseField = document.querySelector("#text-goes-here");

const postText = async () => {
  const text = inputField.value;
  const data = JSON.stringify({ destination: text });

  try {
    const response = await fetch(url, {
      method: "POST",
      body: data,
      headers: {
        "Content-type": "application/json",
      },
    });

    if (response.ok === true) {
      const jsonResponse = await response.json();
      responseField.innerHTML = jsonResponse;
    }
  } catch (error) {
    console.log(error);
  }
};

const displayText = (event) => {
  event.preventDefault();

  while (responseField.firstChild) {
    responseField.removeChild(responseField.firstChild);
  }

  postText();
};

submitButton.addEventListener("click", displayText);

Now onto my server script:

const express = require("express");
const bodyParser = require("body-parser");
const read = require('fs');
const router = express.Router();
const app = express();

const port = 3000;


app.use(express.static(__dirname + "/public"));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


app.get("/", (req, res) => {
    res.sendFile("public/index.html");
})

router.post("/result", (req, res) => {
    console.log(req.body);
    res.send();
});

app.use("/", router);

app.listen(port, () => {
    console.log(`Server running at port: ${port}`)
});

Upon investigating in the dev console, I noticed that even though (response.ok) evaluates to "true", there is an error being thrown into the catch block saying "SyntaxError: Unexpected end of JSON input at postText (script.js:23)"

This error occurs specifically on this line:

const jsonResponse = await response.json();

If anyone can provide some insight into where I might be going wrong, I would greatly appreciate it as I am currently stuck.

Answer №1

This issue occurs when attempting to parse data that does not conform to the JSON format.

"SyntaxError: Unexpected end of JSON input at postText (script.js:23)"

It is accurate to say that the response being returned to the frontend is not valid JSON.

router.post("/result", (req, res) => {
    console.log(req.body);
    // The response is not a valid JSON object
    res.send();
});

To resolve this, you can update res.send() to res.json() and provide a properly formatted JSON object.

res.json({ name:"John", age:30, car:null })

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

Enhancing website functionality with Regex in Javascript

So, here is the code I am working with: var patt = new RegExp("/.+/g"); var device_id = patt.exec("javascript:project_id:256, device_id:2232"); Surprisingly, after running the above code, the value of device_id is empty and I can't seem to figure ou ...

Learn how to call JavaScript code from an HTML file using Ajax

I am encountering an issue with my website. The index.html page contains JavaScript code that triggers an AJAX request to show the content of other.html inside a div in index.html. However, despite the other.html loading correctly, the JavaScript code wit ...

Tips on managing Array indexes in AngularJS

Just diving into the world of Angularjs and I have some JSON files containing an array of car objects that I'm displaying on my webpage. My goal is to have a "button" that, when clicked, will alert me with data specific to that particular button. The ...

Use Angular.js to perform navigation after clicking the "Ok" button on a confirmation box

I encountered a problem with my requirement. I need a confirm box to appear when the user attempts to navigate to the next state/page. Only if the user clicks on the "Ok" button should it proceed to the next state; otherwise, it should stay as it is. Below ...

Creating a unique Angular filter involves combining different techniques and functionalities to tailor

Hey there! I'm just diving into the world of Angular JS and I'm looking to filter any Twitter text that comes back containing a hashtag, and turn that word into a clickable link. For example: If the returned twitter text is "The quick brown #f ...

How to access a particular tab in Bootstrap 5 using an external link

Is there a way to direct users to a specific tab upon clicking a link on another page? Check out the example below: <div class="products-btn"> <a href="products.html#pills-profile">view all</a> </div> On Pro ...

RequireJS is timing out while loading the runtime configuration

I keep encountering a load timeout error with my run-time configuration, specifically with common.js. Although I have set the waitseconds value to 0 for files loaded from common.js, the loadTimeout issue persists for common.js itself. index.html <scr ...

What is the best way to switch back and forth between two div elements?

I've been attempting to switch between displaying div .cam1 and div .cam2, however, I can't seem to get it to work. Here's the code snippet in question: HTML: <div class="cam1"></div> <div class="cam2"></div> CS ...

Can the submit ID value be utilized in PHP?

name="submit" functions as expected. if(isset($_POST["submit"])) <input type="submit" ID="asdf" name="submit" value="Save" class="ui blue mini button"> I want to change it to use ...

Unable to retrieve resource: the server returned a 404 (Not Found) error in a ReactJS and NodeJS application

There was an error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON. Additionally, the server responded with a 404 (Not Found) error when trying to load a resource. I attempted to decode it on the backend with ...

Creating a magical transformation for the bootstrap carousel

Trying to create a bootstrap wizard with a carousel and disable auto-scrolling by setting bs-interval to "false" without success. Here is my code: <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" ...

Is it necessary to utilize Babel with Node.js?

I am aware that Node.js fully supports ES6 now, using version 7.2.1. Recently, I was advised by someone that the current ES6 implementation in Node.js may not be production ready and that I might need to use Babel for a more robust ES6 set-up. After visit ...

What is the best method to fetch a specific post from supabase for showcasing in a dynamic Route with Nextjs14?

I'm currently working on a Next.js application where I am fetching posts from a Supabase database. Everything works fine when retrieving all posts, but when trying to retrieve a single post dynamically using the ID, the screen displays null. Here&apos ...

Receiving no communication from Express Router

Having trouble receiving a response from the server after making get/post requests. I've tried adjusting the order of functions in index.js without success. I also attempted to send a post request using Postman to localhost:8080/register, but the requ ...

Running the test suite in another tab is causing it to fail

I am experiencing an unusual issue in my protractor UI test. During one of the tests, I need to click on a link that opens in a new tab. The test passes when run individually, but fails when run as part of the test suite. I would appreciate it if you coul ...

When using MongoDB/Mongoose, a comment can be pushed into an array upon saving. Within the array, each comment is accompanied by its respective date

I am working with a mongoose model that defines a client's schema. Here is the code snippet: const clientSchema = mongoose.Schema({ Created: { type: String }, kundnr: { type: String, unique: true, required: true }, namn: { type ...

Retrieve an array containing various values of a single element with the help of Protractor

Currently, I am in the process of testing an application that showcases graphs using rickshaw and d3. The tests are being run with protractor and jasmine. It's worth noting that this question is not specific to this particular scenario but rather more ...

Setting up a Node.js application with Nginx on DigitalOcean

While running my application on a DigitalOcean droplet using nginx, I encountered a peculiar issue. The app runs perfectly fine with http, but when switching to https, nginx throws a 502 BAD GATEWAY error. Despite trying various DigitalOcean guides and sco ...

Ways to verify the absence of results in node-postgres

I'm wondering what the postgres database returns when there are no records using node-postgres. try { const { rows: [user] } = await pool.query(`SELECT * FROM "users" WHERE username = $1 LIMIT 1`, [ username ]); console.log( ...

Avoid showing images when the link is not working

I am dynamically fetching images and displaying them on my webpage. return <div className="overflow-hidden "> <Image className="relative w-full h-40 object-cover rounded-t-md" src={cover_url} alt={data.name} ...