The request's body in the PUT method is void

I seem to be having an issue with my PUT request. While all my other requests are functioning properly, the req.body appears to remain empty, causing this error message to occur:

errmsg: "'$set' is empty. You must specify a field like so: {$set: {: ...}}"

Here is the code for the PUT request:

router.put('/books/:name', (req, res, next) => {
    const localdb = db.client.db(process.env.DB_NAME);
    const collection = localdb.collection(process.env.COLL_BOOKS);
    collection.replaceOne(
        { "name": req.params.name },
        { $set: req.body },
        function (err) {
            if (err) throw err
            res.status(201).send(true);

        });

App.js Code:

const express = require('express'),
    app = express();
os = require('os');
const bodyParser = require('body-parser');
const cors = require('cors');
const router = require('./router.js')
require('dotenv').config()


app.use(cors());
app.use(bodyParser.json());

app.use('/api/v1', router);

const port = (process.env.PORT || '3001');

let server = app.listen(port, os.hostname(), () => {
    let host = server.address().address,
        port = server.address().port;
    console.log("Example app listening at http://%s:%s", host, port);
});

Axios Request Code:

 updateItem = newBook => {
        Axios.put(process.env.REACT_APP_API_PATH_BOOKS + `${newBook.name}`, newBook)
            .then(res => {
                this.setState({ newBook: res.data });
                this.props.history.push('/admin');
            })
            .catch(err => console.log(err));
    }

I'm struggling to pinpoint what I might be doing wrong here.

Answer №1

Ensure that there are no middlewares interfering with the body parsing process. For example, you might have a JSON body parser but not sending data in JSON format along with proper application headers.

Could you provide some code context for how you are sending the put request and share the output of logging the req in a pastebin?

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

Storing jQuery output in a global variable can be achieved by assigning the result

Take a look at the Code snippet below - $(function() { $.fn.getPosition = function() { var results = $(this).position(); results.right = results.left + $(this).width(); results.bottom = results.top + $(this).height(); return results; } ...

Encountering the error message "npm unable to locate package.json file" while attempting to execute a nestjs project

Currently, I am diving into a nestjs tutorial on YouTube. Initially, I had set up nodejs and then proceeded to install nest through the @nest-cli command as recommended on their official website using my default bash terminal. My code editor of choice is V ...

Is it possible for Mongoose to consistently return null in place of an error message if no results are found?

Why does Mongoose consistently return null instead of an error when no result is found? Person.findOne({ 'name': 'Ghost' }, function (err, person) { console.log(err); // null if (err) return handleError(err); }); I cannot find the ...

"An issue has been observed with libxmljs compatibility on Node version 12.19.0 specifically on

I am currently using Node version 12.19.0 and NPM version 6.14.8 on a Windows system. I recently attempted to install the latest version, which is 0.19.7, and encountered no installation issues. E:\SS\Service>npm install libxmljs > <a ...

NPM is currently experiencing issues on Windows 7 64bit, freezing during installation and updates

Recently, I noticed that my NPM version stopped functioning properly. This issue seems to have originated when I attempted to update npm a few weeks ago, moving from the 1.4 version packaged with node to a more current 2.x version. Since then, things have ...

Is there a way to configure json-server, when utilized as a module, to introduce delays in its responses

json-server provides a convenient way to introduce delays in responses through the command line: json-server --port 4000 --delay 1000 db.json However, when attempting to achieve the same delayed response using json-server as a module, the following code ...

How to correctly serialize nested maps in JQuery ajax data for sending?

var locationData = { "location" : { "name" : $("#user_loc_name").val(), "street_address" : $("#user_loc_street_address").val(), "city" : $("#user_loc_city").val(), "province" : ...

transfer data from local array to global variable

Need help with returning array values using console.log(array);, currently it's displaying empty value []. Any tips or suggestions would be greatly appreciated. var array = []; var maxLength = 3; var delay = 250; //Shortened the delay var ticker = {}; ...

Does the onChange event fire when the value is modified by the parent element?

let [number, set_number] = useState({x: 1}); <ChildComponent number={number} onUpdate={onUpdateFunction} </ChildComponent> set_number({x: 2}) After running set_number({x: 2}), will this action prompt the execution of onUpdateFunction refere ...

Tips for efficiently delivering the create-react-app index file from your server

I have encountered a challenge in my development work with create-react-app. I am looking to serve the index.html file from the backend initially, but I am facing difficulties in achieving this goal. The main reason behind this desire is to customize the ...

Validation within nested Joi schemas

Need help validating a nested object conditionally based on a parent value. const schema = Joi.object({ a: Joi.string(), b: Joi.object({ c: Joi.when(Joi.ref('..a'), { is: 'foo', then: Joi.number().valid(1), otherwise: Jo ...

Mongoose encounters issues when trying to update a document using findOne() method, as it only

I have a set of fixtures assigned to a specific competitor, displayed in the following format: { "_id": { "$oid": "59dbdf6dbe628df3a80419bc" }, "timeOfEntrance": "1507581805813", "timeOfFinish": null, "competitor": { "$ ...

Issue with updating robot's direction using string in Javascript not resolving

Javascript Developing a simple game where a robot moves on a 5x5 board based on user input commands 'L' (move left), 'R' (move right), and 'F' (move forward) from a starting position while facing North (N). Clicking the Move ...

Locate a subdocument by its unique identifier using the value in the main document

Suppose I have a document with the following structure: { selectedId: ObjectId("57b5fb2d7b41dde99009bc75"), children: [ {_id: ObjectId("57b5fb2d7b41dde99009bc75"), val: 10}, {_id: ObjectId("57b5fb2d7b41dde99009bc75"), val: 20}, ...

Using the combination of Node.js, ZeroMQ, and Socket.io, we can implement scoping per

I am currently in the process of developing a web application using node.js and express to deliver a real-time aprs stream to each user through ZeroMQ and socket.io. The idea behind it is that the node.js app receives the complete aprs stream by subscribi ...

Error with Vimeo SDK: Mysterious Player Issue Post Setup (VueJS)

I have a requirement to showcase multiple videos on a Vue-powered website using a Vimeo player. To achieve this, I have developed a VideoPlayer component specifically designed for each video: <template> <div class="video-element__containe ...

using JavaScript to strip away content following .jpg

var lochash = "#http://www.thepresidiumschool.com/news_image/102%20NRD_7420.jpg&lg=1&slide=0"; I am looking to eliminate or modify the content that comes after .jpg. ...

Leveraging a VueJS prop as a variable in an array mapping operation

Trying to figure out a solution where a variable (prop) can be used in an array map function. The initial code snippet looks like this: var result = this.$store.getters['example/store'].map(a => a.fixed_column) I aim for fixed_column to be ...

Navigating through Objects in Angular 9

I am facing a challenge in Angular 9/Typescript while trying to iterate through the object response from my JSON data. Despite searching for solutions, I haven't found any that work for me. In my JSON, there is a section called "details" which contain ...

This error message occurs when trying to access JSON keys from an object with an invalid operand in the 'in' operation

Check out the fiddle I created here: http://jsfiddle.net/kc11/h6nh1gvw/2/ I'm attempting to extract keys from a JSON string using this code: var keys = $.map(a, function(element,key) { return key; }); . But unfortunately, I keep encountering the er ...