Search code examples
node.jsreactjsjsonforms

Getting an unhandled Rejection (TypeError) while fetching (POST)


I'm following a modified JSON Forms tutorial but runs into problems when adding my own code in order to post the form data to a REST endpoint.

The form is loading fine and I'm able to fill it in with data.

I get Unhandled Rejection (TypeError): Failed to fetch when clicking on the "Submit" button. I'm checking the REST service logs and the request is not reaching through to my controller.

This is my App.js code:

import './App.css';
import { person } from '@jsonforms/examples';
import {
  materialRenderers,
  materialCells,
} from '@jsonforms/material-renderers';
import React, { useState } from 'react';
import { JsonForms } from '@jsonforms/react';
import { Button } from 'react-bootstrap';

const schema = person.schema;
const uischema = person.uischema;
const initialData = person.data;    

function App() {

  const [data, setData] = useState(initialData);
    
  const sendData = () => 
    fetch('http://localhost:8080/message', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });

  return (
    <div className='App'>
      <JsonForms
        schema={schema}
        uischema={uischema}
        data={data}
        renderers={materialRenderers}
        cells={materialCells}
        onChange={({ data, _errors }) => setData(data)}
      />
      <Button onClick={() => sendData()} color='primary'>
        Submit
      </Button>
    </div>
  );
}

export default App;

The REST endpoint is up and running and answers perfectly to ...

curl --location --request POST 'http://localhost:8080/message' \
--header 'Content-Type: application/json' \
--data-raw '{
  "name": "John Doe",
  "birthDate": "1985-06-02",
  "personalData": {
    "age": 34,
    "height": 5.9
  },
  "occupation": "Programmer"
}'

Any ideas what might be wrong?


Solution

  • could you please try this way? If not resolved yet might be a CORS error issue. You need to enable cors on your API, you check more about CORS

    Example:

        const sendData = async () =>  {
            const requestOptions = {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data),
            };
            const response = await fetch('http://localhost:8080/message', requestOptions);
            const data = await response.json();
            console.log(data)
         }