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

Implementing text truncation in JavaScript

I am seeking to transform the INPUT I have into a desired OUTPUT format. pieChart.js stackedColumnChart.js table.js and i want OUTPUT like that(wanna remove .js from ) pieChart stackedColumnChart table ...

Unraveling JSON within JSON using Swift

I have been struggling to decode a Json data structure, specifically the elements within an array. Here is a snippet of the Json data I am working with: { "id": 10644, "name": "CP2500", "numberOfConnectors": 2, ...

Instructions on accessing the subsequent li a starting from a designated location

My goal is to change the link color of the button with the id #idIMMUNOLOGY_9, which has the class .active_default, but I must start from the element with the id #idTERRITORIAL_8. I attempted this approach : $('#idTERRITORIAL_8').parent().find( ...

javascript display error message in innerHTML if passwords do not match

Hello, I found your code to be helpful but I am facing an issue. I want to display a message using innerHTML when the passwords do not match. I have been trying to implement this feature but it is not working for me. Below is my current code. Please provid ...

What is the method for retrieving the fixed information?

I am currently working on a project that involves creating a course-rating API. We have been given a completed angular application to work with, and our task is to set up the routes without making any changes to the Angular app. One of the initial tasks a ...

How can I activate a function or pass a selected value to a different scope variable using AngularUI Bootstrap Datepicker?

Check out this AngularUI Datepicker demo on Plunker: http://plnkr.co/edit/DWqgfTvM5QaO5Hs5dHco?p=preview I'm curious about how to store the selected value in a variable or trigger another function when a date is chosen in the field. I couldn't ...

Displaying errors above the table. Executing ng-repeat in AngularJS

I've been struggling with a seemingly simple issue for hours now. I have a table displaying equipment rows using ng-repeat and input controls, and I want to display validation errors above the table. Here's what I tried: <div class="col-xs- ...

Retrieve all elements from JSON using jQuery

JavaScript: function loadDoc(url) { $.ajax({ url: 'mytestjson', dataType: 'json', cache: false }).success(function (result) { console.log(result); //var txt = result.newBranches[0].newNon ...

Guide to fetching and displaying a complex array API using JavaScript's fetch method

Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API: fetch('https://datausa.io/api/data?d ...

Prevent users from changing dropdown options after a form submission fails using Javascript and Jquery

Currently, I am pursuing the tech degree at Team Treehouse and my third project involves creating an interactive form. To simplify my issue, I will outline it in bullet points: The credit card payment method should be preselected when the page loads. I n ...

Modifying the scope variable does not trigger an update in the AngularJS directive

Recently, I created a small directive that wraps its contents with another template file. The objective is to transform the code like this: <layout name="Default">My cool content</layout> into this output: <div class="layoutDefault">My ...

What could be the reason for not receiving any response from my Firestore query?

Hey there! I'm delving into the world of Firebase for the first time and just set up the Firestore emulator. I've added some data that I want to fetch in my Nextjs app. Once I initialized firebase, this is what my component code looks like: funct ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

Is it possible for gson and retrofit to return null when trying to fetch dynamic JSON data

I am struggling with a dynamic JSON that contains nested objects. I have created POJOs for this data, but the model always appears as NULL and I can't figure out what I did wrong. Here is the JSON snippet: { "status": 200, "message": "Accept ...

What is the best way to determine the dimensions of a KonvaJs Stage in order to correctly pass them as the height/width parameters for the toImage function

Currently, I am using KonvaJs version 3.2.4 to work with the toImage function of the Stage Class. It seems that by default, toImage() only captures an image of the visible stage area. This is why there is a need to provide starting coordinates, height, and ...

Access to a custom Google Map via an API connection

I currently have multiple custom Google Maps that I created using and they are all associated with my Google account. Is it possible to access these maps using the Google Maps JavaScript API? It seems like the API does not work with manually created maps ...

"Enhance your Material-UI ListItems with dynamic ripple colors when using React-Router NavLink

Currently, I am attempting to nest a Material-UI <ListItem button> within a react-router <NavLink>. While functionality is present, I have observed that the ripple colors on the <ListItem button> are being altered by the <NavLink> C ...

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...

What is the optimal approach for moving the dashboard to a separate subdomain in a static Next.js-generated landing page?

Our current setup includes several static pages generated by Next.js using the command next build && next export These pages are hosted on AWS S3. I am wondering if we should create a new app for building a dashboard with Firebase authentication ...

Customize Bottom Navigation Bar in React Navigation based on User Roles

Is it possible to dynamically hide an item in the react-navigation bottom navigation bar based on a specific condition? For example, if this.state.show == true This is what I've attempted so far: const Main = createBottomTabNavigator( { Home: { ...