Server-side access to form data has been restricted

When I make a PUT request from the frontend, I am currently using the XMLHttpRequest and FormData API. However, on the server side, I am not receiving any data such as

req.params, req.body, and req.query
are all empty.

Front-end Implementation

var reportSub = () => {

        var report = document.getElementById('report');

        var formData = new FormData(report)



    let xhr = new XMLHttpRequest();

    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.response)
        }
    }

    var queryString = new URLSearchParams(formData);

    xhr.open("PUT", '/threads/edit', true);
    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
    xhr.send(queryString)

}
 var reportsub = document.querySelector('#repsub');
 reportsub.addEventListener("click",(e)=>{
        e.preventDefault();

        reportSub();
    })

Server-side Code


router.put('/threads/edit',(req,res)=>{

    let board = req.body.board;
    let id = req.body.id;

    console.log(req.query,req.body)

    Board.findById({_id: ObjectId(id)},(error,data)=>{

      if(error)
          res.send(error)

      if(data!==null){
        data.Reprot = true;
        data.save((error,sd)=>{

          if(error)
              res.send(error)

           res.send(sd);   
        })
      } 
      else{
        res.send({"Error":"Id does not exist "})
      }   
    })
})

One possible solution is to hard code the data in the URL for each variable that needs to be passed, which is not ideal. That's why I prefer using the FormData interface to send data.

Answer №1

It seems like there might be a missing library needed for parsing the FormData request in your code. Another approach could be sending the data using JSON as it is text-only, which would make the parsing process simpler. Here's a minimal example that demonstrates this:

server.js

const express = require("express");
const multer = require("multer");
const upload = multer();
const app = express();

app.use(express.static('public'))

app.post('/data', upload.none(), function (req, res) {
    console.log(req.body.favoriteNumber);
    res.send('42 is the only real choice');
});

app.listen(3000, function () {
    console.log('App listening on port 3000!');
});

public/index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <form id="textForm">
        <p>Your favorite number:</p>
        <input type="text" value="42" name="favoriteNumber" />
    </form>
    <button id="send">Send</button>
    <script>
        const sendButton = document.getElementById("send");
        const form = document.getElementById("textForm");
        sendButton.addEventListener("click", () => {
            let xhr = new XMLHttpRequest();

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log(xhr.response);
                }
            }

            const formData = new FormData(form);
            xhr.open("POST", '/data', true);
            xhr.send(formData);
        })
    </script>
</body>

</html>

There's no need to manually set the header in this case, as it's automatically configured and includes the boundary parameter - which you don't need to worry about while coding. The header might look similar to:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryuzeaYvzY77jzcFeA

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

Enhance your React application by making two API requests in

Below is the React Component that I am working on: export default function Header () { const { isSessionActive, isMenuOpen, isProfileMenuOpen, setIsMenuOpen, closeMenu, URL } = useContext(AppContext) const [profileData, setProfileData] = useState({}) ...

Ensure that when adjusting the height of a div, the content is always pushed down without affecting the overall layout of the page

My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code. I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content t ...

Even though I am sending an object through the request, the POST method is still returning an empty object in my req

#expressJs #nodeJs I am experiencing an issue with my post method in ExpressJS. When I submit data from my React form, the post method is returning an empty object instead of the filled object that was passed from the frontend. How can I ensure that the ...

The input text in the Typeahead field does not reset even after calling this.setState

As I work on creating a watchlist with typeahead functionality to suggest options as the user types, I encountered an issue where the text box is not resetting after submission. I attempted the solution mentioned in this resource by calling this.setState( ...

Tips for creating an expression within ng-if

I am struggling with placing an expression inside ng-if that needs to be assessed in order for my content to be shown based on its outcome. This is what I currently have: <a ng-if="abc.status===failure" href="http://localhost:3000/abc/abc">image< ...

Utilize the power of jQuery to easily toggle visibility of an overlay

I have successfully implemented JQuery to show and hide my overlay with great success. Now, I am interested in adding animations to enhance the user experience. After reviewing the jq documentation, I found some cool animations that can be easily integrate ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

Guide on executing a jar file using JavaScript and obtaining a JSON output

Is there a way to execute and capture the output of a jar file that returns a json using javascript? ...

Tips on storing information within a Vue instance

Seeking a simple solution, all I need is to save data retrieved after an AJAX post in the Vue instance's data. See below for my code: const VMList = new Vue({ el: '#MODAL_USER_DATA', data: { user: []//, //userAcc: [] }, met ...

Animating background images using a single data attribute

I'm attempting to create a smooth animation between different background images stored in a single data attribute. The goal is for each image to load sequentially, with the first one appearing immediately and the rest following after a 5-second delay. ...

What is the Next.js equivalent of routing with rendering capability for nested component paths?

I am new to Next.js and so far have been loving the experience. I'm a bit stuck on how to achieve the equivalent of the following code in Next.js These are all client-side routes that render nested components on the user page. The value of ${currentP ...

Managing route rendering in nuxtjs: A guide

I came across Goldpage, a tool that allows for route rendering control. Render Control - With Goldpage, you have the flexibility to choose how and when your pages are rendered. For example, one page can be rendered to both HTML and the DOM (classic serv ...

What is the method for concatenating two strings in JavaScript without any whitespace in between?

When working with two strings involving time, consider the following scenario: var gettime= $("#select-choice-2 :selected").text(); The above code returns a time value in 24-hour format, such as 17:45 However, if you require the time to display in the ...

Encountering issues when attempting to render a function within the render method in React

When attempting to render the gridWithNode function inside the render method, I encountered an error message stating: "Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant ...

Puppeteer: Interacting with login dialog box fields

I am currently facing an issue while attempting to generate a .pdf file from a specific page on our Intranet using Puppeteer and Headless Chrome within Node.js. Generating a .pdf file from a regular webpage poses no challenge, but I am encountering diffic ...

What is the process for generating Json using information from a form?

Recently, I embarked on a project that involves creating online tours via a form filled out by the administrator. The data submitted through the form is then mapped into a Mongoose Schema and transformed into JSON. In the createcontent.js file, I utilized ...

The ejs.renderFile function continues to output logs to the console

I am currently working on a project that utilizes Express.JS with EJS as the view engine. Whenever I use ejs.renderFile, whether directly or with res.render, the function body that is generated gets printed to stdout. This only occurs when the NODE_ENV is ...

Elevate the value within a function and refresh the said function

I'm currently facing a challenge with this particular piece of code, let spin = new TimelineMax(); spin.to($('.particle'), 150, { rotation: 360, repeat: -1, transformOrigin: '50% 50%', ease: Linear.easeNone }); Th ...

Turn off the extra space inserted by DataTables

Help needed with centering table header text. <table class="table table-bordered table-hover center-all" id="dataTable"> <thead> <tr> <th scope="col" style="text-align: center">Nam ...

Generate a random number to select a song file in Javascript: (Math.floor(Math.random() * songs) + 1) + '.mp3'

My current JavaScript code selects a random song from the assets/music folder and plays it: audio.src = path + 'assets/music/'+(Math.floor(Math.random() * songs) + 1)+'.mp3' However, I've noticed that sometimes the same trac ...