如何在一个请求中通过axios api将两个不同的值发送到我的后端?

时间:2019-10-21 18:40:03

标签: reactjs spring-boot axios

我有一个使用REST的Spring Boot应用程序的后端,具有一对多映射。我想指派给看护人,为此,我需要同时发送两个ID,以便我可以找到这些元素。前端是React js和axios

反应页面

import React, { Component } from 'react'
import CaregiverApiService from "../../service/CaregiverApiService";

class AddRelationCaregiverPatient extends Component{

    constructor(props){
        super(props);
        this.state ={
        idPac:'',
        idCare:'',
                       message: null
        }
        this.getOne = this.getOne.bind(this);
    }

    getOne = (e) => {
        e.preventDefault();
        let rel = {idPac: this.state.idPac, idCare: this.state.idCare};
            console.log(rel);
               const { idPac, idCare } = this.state;
CaregiverApiService.getOne(idPac,idCare)
            .then(res => {
                this.setState({message : 'Caregiver added successfully.'});
                this.props.history.push('/patients');
            });
    }

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

    render() {
        return(
            <div>
                <h2 className="text-center">Add Caregiver</h2>
                <form>
                <div className="form-group">
                    <label>Caregiver Name:</label>
                    <input type= "number" placeholder="idPac" name="idPac" className="form-control" value={this.state.idPac} onChange={this.onChange}/>
                </div>

                <div className="form-group">
                    <label>Surname:</label>
                    <input type="number" placeholder="idCare" name="idCare" className="form-control" value={this.state.idCare} onChange={this.onChange}/>
                </div>
                <button className="btn btn-success" onClick={this.getOne}>Save</button>
            </form>
    </div>
        );
    }
}

export default AddRelationCaregiverPatient;

我尝试发出的api请求

  getOne(idPac,idCare)
    {
    return axios.put(CAREGIVER_PACIENT_API_BASE_URL+'/'+idCare+ '/'+idPac);
    }

后端


@RestController
@CrossOrigin
@RequestMapping(value = "/caregiver_patient")
public class caregiver_patientController {
    @Autowired
    private CaregiverService careService;

    @Autowired
    private PatientService patService;
    @PutMapping("/{id}/{id}")
    public ApiResponse<Patient> getOne(@PathVariable int idCare,@PathVariable int idPat){
       PatientViewDTO pp= patService.findPatientByIdPatient(idPat);
        CaregiverViewDTO cc=careService.findCaregiverByIdCaregiver(idCare);
        pp.setCaregiver_idCaregiver(CaregiverViewBuilder.generateEntityFromDTO(cc));
        Patient pat=PatientViewBuilder.generateEntityFromDTO(pp);
        PatientDTO ppat= PatientBuilder.generateDTOFromEntity(pat);
        patService.update(ppat);
        return new ApiResponse<>(HttpStatus.OK.value(), "Patient fetched successfully.",ppat);
    }
//



}

我得到了错误,但我找不到解决办法 “ HTTP400:错误请求-由于语法无效,服务器无法处理该请求。 (XHR)选项-http://localhost:8080/caregiver-patient/[object对象] / [对象对象]” 谢谢!

2 个答案:

答案 0 :(得分:1)

我相信您在此问题上的问题: CaregiverApiService.getOne(idPac,idCare)

idCare上方几行声明为对象:{idCare: this.state.idCare}

因此,该网址包含[object Object]

您尝试过吗:

const { idPac, idCare } = this.state;
CaregiverApiService.getOne(idPac, idCare)

答案 1 :(得分:0)

要在开发时解决CORS异常,只需将app.security.allow-all-origins = true添加到您的application-dev.properties或允许使用以下所有来源:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

没有回答这个问题,更多的是一般性的建议:如果没有ExceptionHandler,找出一个带有请求的Spring Boot服务器确实很烦人。

将此添加到您的项目中以改善生活:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class ExceptionHandlerAdvice {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
        log.warn("Returning HTTP 400 Bad Request for invalid http message", e);
    }
}