I can't seem to get React Fetch and the expressJS post method to cooperate - what could I be overlooking?

I have been diving into the world of React and recently ventured into working with expressJS. However, I encountered an issue with the POST method as the data is not being successfully posted to the server. While I believe my fetching of the post method is correct, the problem might lie within my express file. I have also set a proxy in JsonFile. Perhaps there's something that I am overlooking.

const express = require('express')
const app = express()
const port = 3001
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

app.get('/users', (req, res) => {
    res.json(cars);
})

// GET method route
app.get('/info', (req, res) => {
    res.send(console.log(req))
})


// GET method route
app.get('/', (req, res) => {
    res.send('Hello this is John Server')
})

// POST method route
app.post('/info', function (req, res) {
    const info = {
        first_name: req.body.name

    };

    console.log(info)

})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})
import React from 'react'

class UserForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = { name: '' };
    }

    handleChange = (event) => {
        this.setState({ [event.target.name]: event.target.value });
    }

    handleSubmit = (event) => {
        alert('A form was submitted: ' + this.state);

        fetch('/info', {
            method: 'POST',
            // We convert the React state to JSON and send it as the POST body
            body: JSON.stringify(this.state)
        }).then(function (response) {
            console.log(response)
            return response.json();
        });

        event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <label>
                    Name:
                    <input type="text" value={this.state.value} name="name" onChange={this.handleChange} />
                </label>
                <input type="submit" value="Submit" />
            </form>
        );
    }
}

export default UserForm;

enter image description here

Answer №1

There seems to be a minor issue here. It appears that you used JSON.stringify(), which means you converted the JSON to an object, so you may need to convert it back to JSON in the backend. You could try using JSON.parse() instead, and then you should be able to access your object keys.

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

Using ASP.NET MVC 5, connect JSON to the action parameter

I encountered a problem while developing a basic app using ASP.NET MVC 5. The issue arose when I attempted to convert JSON into an entity. Below is the code snippet: Entity public class PlayListViewModel { public PlayListViewModel() { Track ...

Getting session cookies in getServerSideProps with next js and firebase

In my current Next.js project, I am utilizing Firebase for authentication. To manage the user session, I am creating a session cookie using the Firebase admin SDK within an express backend API that is running on localhost but on a different port. const coo ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Distinguishing the dissimilarity in functionalities between InputProps disabled and disabled in MUI Text

There are various ways to disable the MUI textfield: You can disable it by directly passing the disabled prop. You can also disable it by passing InputProps: {{ disabled: true }}. Or you can disable it by passing inputProps: {{ disabled: true }}. The thi ...

emulate the removal of a material-ui Chip

I'm looking to create a test that removes a material-ui Chip component from my InputTag component. Does anyone have any suggestions on how to make this happen? Here is what I have tried so far: import React from 'react'; import InputTag fro ...

Having trouble with accessing input field in a modal that was generated by TinyMCE React within a Next.JS environment

In my current project, I am utilizing Next.JS and looking to incorporate the TinyMCE editor onto my webpage. Here is the code snippet I have implemented: <TinyMceEditor selector='textarea' initialValue={ props.value } apiKey=<AP ...

Styling the content within Template Strings is not supported by VSCode

Recently, I've noticed that there are two scenarios in which my VSCode doesn't properly style the content within my template strings. One is when I'm writing CSS in a JavaScript file, and the other is when I'm fetching data from GraphQL ...

Tips for properly configuring a session with everyauth and express

I've been working on a simple nodejs application that allows users to log in with Facebook using express and everyauth. I followed the instructions provided in the README tutorial here and set up my app.js file as shown below: var everyauth = require ...

I'm confused as to why redundant data is being transferred over to my URL within a React component

Within my main App.js file, I have implemented the rendering of my Navbar component: import React from 'react'; import { BrowserRouter as Router } from 'react-router-dom'; import Navbar from './components/layout/navbar/Navbar' ...

can you explain which documents outline the parameters that are passed into the express app.METHOD callback function?

As a beginner in javascript and nodejs, I often struggle with understanding callback functions. One thing that particularly confuses me is determining what arguments are passed into a callback function. Let's consider the following example: app.get( ...

Configuring Axios header in Java backend based on the value stored in the express session

I am currently working on a frontend app using node.js express for server-side rendering. This app calls java backend endpoints and I use Axios to make the requests. A specific header named "agent-id" needs to be set in every request that is sent from expr ...

Stack screen not visible on React Native navigation

I'm currently utilizing the React Native Navigation library for routing. However, I've encountered an issue with the code below that doesn't seem to be functioning as expected. My objective is to set up two screens - one for login and the o ...

Toggle the visibility of the element or component with a simple click of a button

I am facing an issue where I am unable to change the state by clicking a button. Here is the code snippet in question: changeAllFun = () => { this.setState = ({ showBadTable: '1', }) } changeBadFun = () => { this.s ...

Encountering issues with link button redirection

I have a question regarding a Link element and CustomButton element with an onClick handler. < Link to = "/dashboard" style = { linkStyles } > < CustomButton text = "Login" onClick = { handleSubmit } /> < /Link> The code ...

How can users be queued in a web application built with the MERN stack?

I am in the process of creating a MERN application for online teacher-doubt resolution. Here is how the system will operate: A user using the app will click on the "Ask Doubt" button next to the specific teacher. The user will then make a payment. ...

Why Isn't Formik onChange Updating the Field Value?

Hello everyone, I'm encountering a strange issue with a Formik form that uses Select fields. Here's what I would like it to do: Select A allows you to choose a County Select C allows you to select a City. Whenever a user picks a different opti ...

Step-by-step guide to automatically generating :hover colors in custom color objects for buttons in Material-UI V5

Currently, I am utilizing the latest version of MUI v5 to define custom colors for my theme provider. However, I have observed that there is no color change on hover state. Is there a specific parameter that needs to be included in main to automatically ge ...

How to eliminate the issue of horizontal scrollbar appearing in Material UI Datagrid

I'm currently utilizing the Mui datagrid component and encountering a horizontal scrollbar issue. const columns = [ { field: 'fileName', headerName: 'File Name', flex: 2, headerClassName: 'table-header' }, { field ...

Create RESTful routes based on the attributes of the resource

When dealing with a User entity and needing to retrieve its data using different criteria or routes, such as by id or username, what is the recommended approach for naming these specific endpoints: GET /users/:id GET /users/username/:username GET /users/ ...

What steps should be taken to resolve the undefined index error in the context of using Jquery Ajax with PHP

Currently, I am utilizing Jquery, Ajax, and PHP in an attempt to send a variable for writing into a MySQL database. Although the Ajax request is being initiated, the PHP script seems unable to pick up the variable. The reason behind this issue remains uncl ...