0

我正在关注修改后的JSON 表单教程,但在添加我自己的代码以将表单数据发布到 REST 端点时遇到问题。

表单加载正常,我可以用数据填充它。

我收到未处理的拒绝(TypeError):单击“提交”按钮时无法获取。我正在检查 REST 服务日志,但请求没有到达我的控制器。

这是我的 App.js 代码:

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;

REST 端点已启动并正在运行,并完美地回答...

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"
}'

有什么想法可能是错的吗?

4

1 回答 1

0

你能试试这个方法吗?如果尚未解决,则可能是 CORS 错误问题。您需要在您的 API 上启用 cors,您可以查看有关CORS的更多信息

例子:

    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)
     }
于 2021-10-28T09:14:28.107 回答