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

How do you find the parent router's path in Express?

If I want to create two separate instances within "subfolders" in the URL, in my app js file I define it like this: var routes = require('./routes/index'); app.use('/myapp1', routes); app.use('/myapp2', routes); The interna ...

Open the iframe link in the main window

As a newcomer to this platform, I am trying to figure out how to make a link open in the parent page when clicking a button within an iframe. Currently, my code opens the link in a new window. <html> <body> <form> <div class ...

Exploring AngularJS and Jasmine: Testing a controller function that interacts with a service via $http

I encountered an issue while testing a controller that relies on a service. The problem arises because the service is currently set to null in order to focus solely on testing the controller. The current test setup is failing due to the BoardService being ...

What is the best way to dynamically assign a value to an anchor tag upon each click using jQuery?

How can I pass a value to an anchor tag on every click using jQuery? I am encountering an issue with my current code where the value is not being retrieved when I click the button. //HTML snippet <button id="a-selectNm" data-a_name="<?php echo $row[ ...

Mastering Interpolation in React with TypeScript is essential for creating dynamic and interactive UI components. By leveraging the

Incorporating and distributing CSS objects through ChakraUI presents a simple need. Given that everything is inline, it seems the main issue revolves around "& > div". However, one of the TypeScript (TS) errors highlights an unexpected flagging of ...

ScrollReveal.js won't function as intended

https://i.stack.imgur.com/SOQEk.png Looking to utilize the popular ScrollReveal.js created by Julian Lloyd (ScrollReveal) Despite following instructions from various sources, the script is not producing the intended effect. Steps taken to make it work: ...

What is the best method to obtain the combined total of values within a mongoose subdocuments array while querying the parent object?

I am in the process of developing a more advanced hello world application using express and mongoose. Let's assume I have the following Schemas: const pollOptionsSchema = new Schema({ name: String, votes: { type: Number, default: 0 } }) ...

What sets apart getStaticProps + fallback:true from getServerSideProps?

I have gone through the Next.js documentation multiple times, but I am still struggling to grasp the difference between using getStaticProps with fallback:true and getServerSideProps. From my understanding: getStaticProps getStaticProps is rendered at b ...

Why is it unnecessary to include a callback when using a setState function from useState as an argument in useEffect?

While working with a function from my component in the useEffect arguments, it is recommended to write a callBack so that it is memorized and used as a dependency of the useEffect. Without this, there is a warning. However, when using the setState of use ...

Tips for refreshing a D3.js bubble chart with live JSON data updates

Currently delving into d3 and experimenting with transforming a static bubble chart into a dynamic one that adjusts by removing or adding bubbles based on JSON changes. I am aiming to have the JSON file refreshed every 5 seconds to update the bubble chart ...

`vue.js: li element tag numbers not displaying correctly`

Issue with Number list not displaying correctly using Vue.js I have tried sending it like this. Is there a fix for this problem? This is the code snippet I used to output in Vue.js: p(v-html="selectedProduct.description") Snapsho ...

Upon sending a POST request to http://localhost:5000/getData, a 404 error (Not Found) was encountered while using axios

As a newcomer to react and node.js, I have set up a fake server running on port 5000 with an API (http://localhost:5000/getData) that contains a hardcoded array of objects. My goal is to add a new object to this API from my react frontend running on port 3 ...

How can you retrieve an array of multiple property values from a collection of dynamic objects?

I am currently working with a dynamic JavaScript object array that has varying structures. For example: var someJsonArray = [ {point: 100, level: 3}, {point: 100, level: 3}, {point: 300, level: 6} ]; At times, it may have a different combination lik ...

Conceal the Angular Bootstrap modal instead of shutting it down

I am utilizing Angular Bootstrap Modal to launch multiple modals, including a video player. http://angular-ui.github.io/bootstrap/#/modal My goal is to maintain the video's current position even when the modal is closed. This way, when I reopen the ...

Obtain a file from React Native in order to upload an image, just like using the `<input type="file" onChange={this.fileChangedHandler}>` in web development

After experimenting with different methods, I attempted to achieve the desired result by: var photo = { uri: uriFromCameraRoll, type: 'image/jpeg', name: 'photo.jpg', }; and integrating axios var body = new FormData( ...

Retrieve data via AJAX using a combination of JavaScript and ASP

Can someone help me figure out how to retrieve the value of value1 on my server-side ASP using Javascript? I am using this Ajax code but unsure of how to do it. In my serverside code, I would like to have something like <% var newdata = value1 (which ...

I'm having trouble getting the function inside onLoad to run in my Next.js project - can anyone help

While I was exploring nextjs.org and following the tutorial, I encountered an issue where the function inside onLoad wasn't executing. It's puzzling because there was no call made to that link in the networks tab of my browser's developer to ...

Utilizing the power of AngularJS, NodeJS, and Mongoose to create dynamic and

I am relatively new to the world of JavaScript. I am currently experimenting with using pie charts from Highcharts (www.highcharts.com) in conjunction with AngularJS. In the example provided below, everything works smoothly, except for the fact that the "i ...

Tips for transferring a calculated value from a child component to a parent component in ReactJs

In my current project, I am faced with the challenge of passing a calculated value from a child component back to its parent. The child component is designed to utilize various user inputs to compute a single value that needs to be returned to the parent. ...

Display the entire HTML webpage along with the embedded PDF file within an iframe

I have been tasked with embedding a relatively small PDF file within an HTML page and printing the entire page, including the PDF file inside an iframe. Below is the structure of my HTML page: https://i.stack.imgur.com/1kJZn.png Here is the code I am usin ...