0

我正在使用 ReactJs 和 React-Hook-Form 创建一个应用程序。我的目的是使用 Fetch API 向服务器(Java-Spring 启动)发出 POST 请求。

下面是我的代码: React 组件 - SalesmanForm:

import { useForm } from "react-hook-form";

import "./SalesmanForm.css";

const SalesmanForm= () => {
    const { handleSubmit, register, errors } = useForm();

    const createSalesman = data => {
        return fetch('http://localhost:1235/salesman/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
            .then((response) => response.json())
            .then((data) => {
                console.log("Create Success: ", data);
            })
            .catch((error) => {
                console.error("ERROR: ", error);
            })
    }

    return (
        <form onSubmit={handleSubmit(createSalesman)}>
            <label>First Name</label>
            <input
                name="firstname" defaultValue="firstname"
                ref={register(
                    {
                        required: true, maxLength: 50
                    }
                )}
            />
            {errors.firstname && <p>This field is required</p>}

            <label>Last Name</label>
            <input
                name="lastname"
                ref={register(
                    {
                        maxLength: 50,
                        validate: value => value !== "" || "This field is required"
                    }
                )}
            />
            {errors.lastname && errors.lastname.message}

            <label>Phone Number</label>
            <input
                name="phonenumber"
                ref={register(
                    {
                        maxLength: 50,
                        validate: value => value !== "" || "This field is required"
                    },
                )}
            />
            {errors.phonenumber && errors.phonenumber.message}

            <label>Address</label>
            <input
                name="address"
                ref={register(
                    {
                        maxLength: 300
                    },
                )}
            />

            <input type="submit" />
        </form>
    );
};

export default SalesmanForm;

API - SalesmanEnpoint:

@RestController
@RequestMapping("/salesman")
@CrossOrigin(origins = "http://localhost:3000")
@Api(value = "Salesman Endpoint")
public class SalesmanEnpoint {
    @Autowired
    SalesmanService salesmanService;

    @RequestMapping(value = "/", method = {RequestMethod.POST})
    @ApiOperation("Add new Salesman")
    public void addNewSalesman(@RequestBody SalesmanDto salesmanDto) {
        salesmanService.saveSalesman(salesmanDto);
    }
}

服务实施:

@Service
public class SalesmanServiceImpl implements SalesmanService {
    @Autowired
    SalesmanRepository salesmanRepository;

    ModelMapper modelMapper;

    @PostConstruct
    private void init() {
        modelMapper = new ModelMapper();
    }

    @Override
    public ResultObject<SalesmanDto> saveSalesman(SalesmanDto salesmanDto) {
        ResultObject<SalesmanDto> result = new ResultObject<SalesmanDto>();
        SalesmanEntity salesmanEntity = new SalesmanEntity();
        modelMapper.map(salesmanDto, salesmanEntity);
        SalesmanEntity slsmanEntity = salesmanRepository.save(salesmanEntity);
        modelMapper.map(slsmanEntity, salesmanDto);
        result.setData(salesmanDto);

        return result;
    }
}

我的问题是当使用 Fetch Api 将输入数据提交到服务器时,所以我的数据在发送请求期间已更改为空值。我不知道这是为什么?

任何人都可以向我提出有关问题和解决方案的建议。

太感谢了!

4

0 回答 0