The error message "Cannot set headers after they are sent to the client" is indicating that the headers have already been sent to the client and

What could be causing this error to appear?

It seems like the only route available is through post method. I can't seem to find any other place where a header is being sent.

I'm also puzzled as to why body.content is showing up as undefined, even though an object is being sent and the header is set to json. Interestingly, the body parser or app.use(bodyParser.json()) isn't working either.

"express": "^4.17.3"

Your assistance is greatly appreciated

const express = require("express");
const app = express();
app.use(express.json());

app.post("/api/persons/", (req, res) => {
  const body = req.body;
  //if body has no data return here
  console.log(body.content);
  if (!body.content) {
    return res.status(400).end().json({ error: "missing content" });
  }
//generate entry in list
  const person = {
    number: body.number,
    name: body.name,
    id: generateID(),
  };
  persons = persons.concat(person);
  res.json(person);
});

Answer №1

.finish stops the response. If you use .finish, you won't be able to send anything further. Simply omit that part and use .json to send the information to the client, without abruptly ending the response.

  if (!body.content) {
    return res.status(400).json({ error: "missing content" });
  }

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

Can you explain the significance of this code snippet 'true <=> false'?

Today I came across this piece of code: true <=> false. I'm a bit confused by it and don't really understand how it works. If anyone could shed some light on this expression for me, I would greatly appreciate it. For reference, this code ...

Filtering Gmaps markers using angular and javascript: A step-by-step guide

This code is designed to show markers on a map based on selected dates. Only the markers created during the chosen time period will be visible. I am monitoring a value from an external JavaScript script called obj.dateRangeSlider("values"). as shown belo ...

How to Delete Elements from an ngList Array in Angular

I encountered an issue while utilizing ngList in a text box to exchange data with my server. The problem arises when I attempt to delete items from the generated array directly, as it does not reflect the changes in the input field. The main concern is th ...

Refresh outfit designs or retrieve information from fragment shader post-processing

While working on image processing in the fragment shader (specifically thresholding), I find myself wanting to access the processed result from JavaScript so that I can save the modified image using standard JavaScript methods. I send the original texture ...

How to achieve padding of strings in JavaScript or jQuery

Does anyone have information on a similar function in jQuery or JavaScript that mimics the prototype toPaddedString method? ...

Is it possible to utilize JSON in Struts 2 to bypass the necessity of tags and page mappings?

Lately, I've been pondering the concept of a design approach that utilizes unmapped pure HTML and JavaScript pages pulling JSON data from Struts 2. This means no action mappings are required, resulting in relative page references with minimal need for ...

Working with AJAX PHP variables within JavaScript

The code below was previously functioning correctly: var xmlHttp var layername var url function update(layer, url) { var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere if(xmlHttp==null) { alert("Your browser is not supporte ...

What could be the reason for Express.js failing to correctly interpret POST parameters?

Here is the POST data I'm working with: account_id 1231 limit 3 ordertype limit quantity 1 symbol USDJPY transaction_type buy Within my code, I've defined the following variables: var account_id = req.param('account_id', ...

Is it possible to convert a .gif file into a jpeg image format for mobile display on my Gatsby website?

I'm looking to convert a .gif file into a mobile.png image for my Gatsby site, but I'm struggling to find the right resources. Does anyone have suggestions on how I can achieve this? Here is the frame: https://i.sstatic.net/IjYv4.png ...

Utilizing the power of Vue.js version 2.x alongside the sleek features of Bootstrap

I'm currently experimenting with incorporating Bootstrap 5 into Vue (2.x) without relying on any third-party libraries. My approach involves creating a custom wrapper for select Bootstrap components that I intend to utilize. For guidance, I've b ...

Tips for obtaining a JSON body enclosed in double quotes in Python?

This python3 code attempts to load JSON data from a file called "sample.json" and then make a POST REST API call. import json with open('sample.json' ) as request_file: post_data = json.load(request_file) print(requst_data) headers = {& ...

Utilizing HTML 5 Video and the src Attribute in Vue Components

I am facing an issue with loading an HTML 5 video dynamically on my page. I am using vue for this purpose and in my js controller, I set a variable containing the video path. Here is how I am trying to use the variable in my page: <video width="450" co ...

I am attempting to activate the HTML5 color picker's popup using JQuery

Is there a way to open a color picker in a popup window when an input[type=color] is clicked, using JavaScript? HTML <div id="customColorPick"></div> <input id="customColorPickInput" type="color" /> JQuery $("#customColorPick").click( ...

Is it possible for Spotify to automatically provide me with a new token once the old one has expired?

The Spotify token expires after 1 hour, requiring a new one to be pasted. Is there a way to automatically fetch a fresh token when the old one becomes invalid? Is it possible to automatically retrieve and store this token? I plan to store the token in a ...

Exploring the connection between two divs using onmouseover and onmouseout events in JavaScript

I am currently working on creating a function that displays a button when the mouse hovers over an element and hides it when the mouse is moved away. The example below illustrates my issue: ------------------------------------------------------------ - ...

Sending AJAX data from VIEW to CONTROLLER in PHP (MVC) using AJAX: A step-by-step guide

I have a page at http://visiting/blog. The Controller contains two methods: action_index and add_index. When Action_index() executes, it returns pages with indexes. On the other hand, Add_index() invokes a model's method called add_data(), which inse ...

Utilizing d3 for Nested jQuery Accordions

I'm facing a challenging issue trying to nest jQuery accordions using d3. The difficulty arises from the complexity of creating HTML structures like the one below with nested accordions, and utilizing d3's nest and data binding functionalities: ...

Reading Json information in flutter

Hey there, I'm working with a JSON file and trying to display the data on the screen. However, nothing is showing up, and I suspect it might be due to an issue with my implementation. class TestScreen extends StatefulWidget { const TestScreen({Key? ...

Which of the two async functions will be executed first?

const [counter, setCounter] = useState(0) Consider the scenario where we have two asynchronous functions, func1 and func2, both of which are responsible for updating the counter state. It is specified that func1 is supposed to execute before func2. async ...

Unable to adjust the padding of the material UI Select component

I'm having trouble adjusting the padding of the Select component in order to align it with the size of my other text fields. Despite knowing that I need to make changes to nested components, I have yet to discover a viable solution. <div className ...