首页 > 解决方案 > axios 向 springboot 后端发送请求

问题描述

我正在尝试将 formData 发布请求(使用 axios)发送到我的后端(springboot),但我不确定正确的方法。我的计划是将数据通过控制器传递给将使用它的服务。

Axios 调用 -

startStreamLocation() {
  const location = new FormData();
  location.set("accuracy", this.accuracy)
  location.set("lat", this.lat)
  location.set("lng", this.lng)
  location.set("timeStamp", this.timeStamp)

  axios.post("http://localhost:8080/api/v1/location/request-location", location,
      {headers: {'Content-Type': 'application/json'}})
},

控制器 -

@PostMapping(value = "request-location")
public ResponseEntity<?> requestLocation() {

    connectionRequestService.addDataToStream();
    return new ResponseEntity<Authenticator.Success>(HttpStatus.OK);
}

服务 -

   public void addDataToStream() {
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
        AmazonKinesis kinesisClient = AmazonKinesisClient.builder()
                .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
                .withRegion(awsRegion)
                .build();

    PutRecordsRequest putRecordsRequest  = new PutRecordsRequest();
    putRecordsRequest.setStreamName("location-stream");
    List <PutRecordsRequestEntry> putRecordsRequestEntryList  = new ArrayList<>();
        PutRecordsRequestEntry putRecordsRequestEntry  = new PutRecordsRequestEntry();
        putRecordsRequestEntry.setData(ByteBuffer.wrap(( INJECT DATA HERE ).getBytes()));
        putRecordsRequestEntry.setPartitionKey(String.format("partitionKey-%d"));
        putRecordsRequestEntryList.add(putRecordsRequestEntry);

    putRecordsRequest.setRecords(putRecordsRequestEntryList);
    PutRecordsResult putRecordsResult  = kinesisClient.putRecords(putRecordsRequest);
    System.out.println("\nData sent successfully... \n" + putRecordsResult);
    try {
        Thread.sleep(1000);
    }
    catch (InterruptedException exception) {
        throw new RuntimeException(exception);
    }
}

标签: javaspring-bootapiaxiosamazon-kinesis

解决方案


由于您想将表单数据发送到服务器,因此您需要将Content-TypeAxios 调用中的标头更改为multipart/form-data. 这有助于服务器了解客户端发送的资源类型。

在服务器端,您需要读取此表单数据。我可以想到以下两种方法来做到这一点

  1. 用于@RequestParam读取单个表单键。例如,如果我的表单数据包含一个名为 的键Foo,我会在服务器端读取它,因为
    @PostMapping(value = "/form-data")
    public void readFormData( @RequestParam(value = "Foo") String foo )
  1. 用于@RequestBody将表单数据映射到MultiValueMap可以像法线贴图一样读取的数据。这是相同的代码片段
    @PostMapping(value = "/form-data")
    public void readFormData( @RequestBody MultiValueMap<String,String> formData )

推荐阅读