I am experiencing challenges with utilizing the fetch() function and am unable to retrieve the data

I'm currently struggling with integrating Google's reCaptchaV3 into my website, particularly when using the fetch() function. Here is the code snippet I have developed so far:

function sendData(name, email, captcha) {

    const info = JSON.stringify({
        name: name,
        email: email,
        captcha: captcha
    });

    fetch('/verifycontact', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'mode': 'cors'
        },
        body: info
    })
    .then(res => { 

        alert(JSON.stringify(res));

        res.json()})
    .then(data => {
        alert('msg: ' + data.msg + ', score:' + data.score);
    }) 
}

When attempting to print out or log the info object, it works before the first then.(). However, trying to log or alert the res object results in an empty response like this:

{}

Is there something crucial missing from the code? Perhaps related to the headers? I am also noticing that on my server side when I try to console.log(req.body), it seems to be empty as well. The **body object received by my server looks like this:

{ success: false, 'error-codes': [ 'invalid-input-response' ] }

Answer №1

After some investigation, I finally pinpointed the issue. It turned out that utilizing bodyParser was necessary in order to correctly parse the body.

To resolve this, I incorporated the following middleware into my express router. Below is the code snippet for configuring bodyParser:

router.use(bodyParser.json({
    verify: (req, res, buf) => {
        req.rawBody = buf;
    }
}));

In addition, I integrated the following middleware into my route handler:

bodyParser.raw({ type: 'application/json' })

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 to fill an HTML template using ngFor without using a JSON array

Is there a way to fill the HTML with basic JSON like below: { "id": 34, "name": "Tip 33", "description": "Tip description 33", "created_at": "2018-01-26 18:59:19", "updated_at": "2018-01-26 18:59:19" } The code i tried using was: < ...

Check if certain entries in the JSON object already exist by iterating through it

As I work on iterating over a JSON object to verify the existence of certain entries, my current JSON data structure is outlined below: [ { "title": "scname", "html": "<div><iframe src=/scenario/test3dx ...

Difficulty encountered while deploying a React application on Netlify

I followed the instructions on a Medium link to deploy my React application on Netlify: To set up the production mode, I utilized an express server for defining build scripts. After creating the build scripts on my local machine, I uploaded them to the Ne ...

Exploring the Node Promise Chain: Utilizing Local Functions and Managing Multiple Value Passing in a Code Review

Upon reviewing the code provided, several questions have arisen: #1 I am curious about the best way to make the values returned by the bluebird.all functions accessible in subsequent functions. Is using the this-context a viable option without declaring t ...

Retrieve all instances of a key-value pair within an object that share the same key

Here is some JSON data: [{"name":"David","text":"Hi"},{"name":"Test_user","text":"test"},{"name":"David","text":"another text"}] I am l ...

What is the level of visibility in Nextjs?

Is it safe to expose the sources of files located in the 'pages/' directory? For instance, if you set up a page specifically for administrators at pages/admin and restrict access through Middleware, does this enhance security measures? ...

I possess a solitary div element that requires dynamic replication

I have a single container and an unspecified number of rows of data. I want to display this data on HTML cards that are generated dynamically based on the number of rows. For example, if there are 10 rows of data, I need to create 10 card elements with ea ...

Discover the best places to master AJAX

Although I have come across some related questions here, none of them exactly match mine. I am aware of excellent resources like code-school and code-academy where you can improve your PHP and JS skills by coding directly on the website. However, I am wo ...

Javascript: recursive function fails to return existing value

I'm attempting to recursively loop through an array in search of a key that matches a specified regex pattern. Once the condition is met, the loop should halt and return the value of the key. The issue I am facing is that although the loop stops corr ...

PHP Foreach function generates distinct arrays in a separated manner

The array generated within a foreach loop is individual, as shown in the example below. It is necessary for them to be contained within a parent Array. Array ( [0] => Array ( [url] => https://example.com/product/osaka-entry-t ...

Issue encountered while attempting to generate a Jquery button

I seem to be facing some difficulties as I have successfully completed this task before. Currently, I am dynamically adding HTML code: ...<td><label><input type=\"checkbox\" checked=\"checked\" class=\"Activechk fo ...

Explore the properties within an array of objects through iteration

Here is the array I'm working with: const myArray = [{ id: 1, isSet: true }, { id: 2, isSet: false }, ...]; I only need to iterate over the isSet properties of the objects, ignoring all other properties. Initially, I attempted the following solution ...

RegEx for constraining string length

I am attempting to identify all instances where the length of a string is more than 1. This is the regex I am using: string.match(/\B\w+(?=\w)/gi); I also attempted this approach: string.match(/^\B\w+(?=\w){2,}$/gi); Unfor ...

Instructions for using Python to split distinct data in a JSON array by employing a vertical pipeline as a delimiter

Displayed below is a json string split into 2 different lines: {""creditNoteId"":""BSA11130181-S7"",""creditNoteUrl"":""www.twitir.com""} {""creditNoteId"": ...

Optimal method for file uploading with Node.js

How can I effectively manage file uploads in node js? I would like users to be able to upload profile images with the following specifications: -Validated size of at least 200 * 200 -Accepted file formats are png, jpg, jpeg, or gif -Additional functi ...

I am facing an issue with the routing functionality in the Quasar framework for Vue 3

I seem to be having an issue with my code where no matter what route I give, it only takes me to the home page. Specifically, when I give the path "auth", it still redirects me to the home page. Can someone please help me understand why this is happening a ...

Execute local server's unit tests using a Gulp task

I am currently faced with the challenge of running automated unit tests in the terminal for a library application that utilizes the History API internally. To achieve this, I am utilizing Babel to transpile and consolidate my Mocha/Chai/Sinon unit tests in ...

Creating a Next.js dynamic route that takes in a user-submitted URL for customization

Currently, I have implemented the Next.js Router to facilitate the display of different dashboards based on the URL slug. While this functionality works seamlessly when a button with the corresponding link is clicked (as the information is passed to the Ne ...

What steps should I take to prompt Postman to interact with a Web API?

I have recently installed the Postman plugin for Chrome and I am curious about how to use it to call my web API. Currently, I am making an AJAX call in JavaScript with the following code: alert("Getting security token"); // Do AJAX call to get security t ...

Using Angular route resolve to handle the sessionStorage login status

I have successfully created a login system using Angular JS. Once the user logs in, a session storage variable is set and they are redirected to a dashboard page (which should only be accessible when logged in). $window.sessionStorage["isLoggedIn"] = true ...