【问题标题】:Getting an unhandled Rejection (TypeError) while fetching (POST)获取 (POST) 时收到未处理的拒绝 (TypeError)
【发布时间】:2021-12-13 11:39:13
【问题描述】:

我正在关注修改后的 JSON Forms tutorial,但在添加我自己的代码以将表单数据发布到 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"
}'

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

【问题讨论】:

    标签: node.js reactjs jsonforms


    【解决方案1】:

    你能试试这个方法吗?如果尚未解决,则可能是 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)
         }
    

    【讨论】:

    • 不,这没有帮助。同样的错误。我按照说明如何在我的 API (spring.io/guides/gs/rest-service-cors) 上启用 cors,但没有成功。
    • 您是否在其他应用上测试过您的 API?像邮递员
    • 我一直在使用来自终端的 curl 命令,如上所示 - 如果这就是你的意思吗?我可以专门试试 Postman ...
    • 是的。从 Postman 调用服务可以正常工作。
    • 我正在更正我之前关于 CORS 的评论。在使用 @CrossOrigin 注释我的资源后,它现在可以正常工作了。
    猜你喜欢
    • 2020-07-15
    • 2017-11-20
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2022-01-03
    • 2023-04-06
    • 1970-01-01
    • 2021-01-06
    相关资源
    最近更新 更多