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

Create object keys without relying on any ORM or database management systems like mongoose or mongodb

Exploring a Mongoose Object: recipe = { "ingredients": [ { "_id": "5fc8b729c47c6f38b472078a", "ingredient": { "unit": "ml", "name" ...

Is it necessary to release a new library version for non-functional updates?

As the maintainer of several JavaScript libraries, I often find myself needing to update dependencies that don't necessarily require any functional changes. This is especially true when my library is not impacted by a breaking change in one of its dep ...

Utilizing JavaScript and JSON to Retrieve Array Elements by Key Names as Indexes

I'm looking for a way to access elements in an array using unique key names instead of numerical indexes. Specifically, I'm developing a Discord bot where each server has its own settings. When a message is sent on a server, I need to retrieve th ...

What could be the reason for the undefined initial state in my vuex store?

I am facing an issue with vuex-typescript where the initial state is always undefined. However, it works fine when I reset the state and refresh the window. Below is my setup for a simple module: import Vue from "vue"; import Vuex from "vuex"; import { m ...

Enable the execution of a function only once a specific period of time has elapsed

Here's the scenario I'm dealing with: In a fun group chat with my friends, I created a giphy bot that responds to /giphy [terms] messages by posting the top result for those terms. However, my friends started abusing it by spamming the chat. To ...

A versatile multi-select jQuery widget featuring the ability to choose options within a specific opt

I am on the hunt for a cool jQuery tool that has the following characteristics: It enables you to create multiple groups, such as: Group 1 - Sub 1 1 - Sub 1 2 - Sub 1 3 Group 2 - Sub 2 1 Group 3 - Sub 3 1 - Sub 3 2 By clicking on Group 1, for instance, ...

Issue with Node Canvas/Resemble.js: The image provided has not finished loading during the load operation

Recently, I encountered a challenge while trying to utilize Resemble.js in a node environment. Despite some initial complications with installing canvas/cairo due to OS X Mavericks/XQuarts and Homebrew issues, I eventually succeeded. After making signific ...

javascript increment variable malfunctioning

Below is the script I am working with: $(function() { var fileCount = {{$image_counter}}; $('#remove-file').click(function() { fileCount--; }); if (fileCount >= '5'){ $("#d ...

Should we enable client-side validation and unobtrusive JavaScript in the Web.config file?

I'm currently working on an ASP MVC application, where all form and UI code is written in AngularJS for validation purposes. I didn't use any HTML helpers. Do I need to include the entries ClientValidationEnabled and UnobtrusiveJavaScriptEnabled ...

The SharedArrayBuffer does not exist in this context

A new library, react-canvas, has been causing some trouble for me. Lately, an error message keeps appearing with the <p> tag in the canvas area where it should be displayed on browsers like Chrome. The framework I'm using is nextjs, and I&apos ...

Passing variables to all routes in Express is a useful way to ensure that data

I am currently working on developing the APIs for my web application using nodejs/expressjs. In order to send certain variables to all APIs, such as site title and description, I am looking for a new approach. It seems that the old solution of using dynam ...

I'm looking to add a price ticker to my html webpage. Does anyone know how to do this?

PHP Code <?php $url = "https://www.bitstamp.net/api/ticker/"; $fgc = file_get_contents($url); $json = json_decode($fgc, true); $price = $json["last"]; $high = $json["high"]; $low = $json["low"]; $date = date("m-d-Y - h:i:sa"); $open = $json["open"]; ...

Strange rendering issues when using the react material-ui dialog

Exploring the Project Recently, I developed a front-end project focusing on a delivery service using React and Material UI. One interesting feature I added was a Dialog window that pops up when users click on an item, allowing them to customize it. Here i ...

Retrieve the currently logged-in user whenever the component is rendered using React's Context API

For my small React project, I am utilizing ContextAPI. Whenever I hit the /login endpoint, I store the user's token using an HttpOnly Cookie. Below is the code for UserContext.js, which encapsulates all components (children) within App.js import axio ...

Navigating to URL with Query String correctly using Express

Below is the code I currently have: app.get('/', function (req, res) { req.query.searchQuery = 'test2' res.redirect('/search'); }); app.get('/search/', function (req, res) { var searchQuery = req.query.search ...

Checkbox Hierarchy: Children marked as either Checked or Unchecked based on parent selection

Hello, I have a form that contains nested checkboxes on three levels. Using jQuery, I am trying to check/uncheck all the children when I check a parent level... and if any of the children are unchecked, uncheck the parent as well. I have attempted this m ...

error occurred while looping through json array

i am encountering an issue with a code that keeps returning an "undefined" message instead of the expected HTML output. Purpose of function: the aim of the following function is to display notifications in a manner similar to those on Facebook. The code se ...

The thickness of the line on the Google line chart is starting to decrease

Currently, I am utilizing a Google line chart in my application. However, I have noticed that for the first two data points, the lineWidth is thick, while for the last two points it is very thin. How can I resolve this issue and ensure that the lineWidth r ...

Unhook, add at the beginning, and set requirements jQuery

There are two clickable div elements that can switch classes when clicked. If the first one contains "1", it will be given a class of "active". If the second one contains "2", it will have the class "active" while removing the class from the first one. &l ...

What steps can be taken to resolve the vulnerability in webpack-pwa-manifest?

Looking for solutions to address the [email protected] and minimist vulnerability. I attempted removing node/modules and package-lock.json, followed by a fresh npm installation, but the issue persists. Any suggestions would be greatly appreciated. Scr ...