Axios 向 springboot 后端发送请求

时间:2021-05-12 04:11:05

标签: java spring-boot api axios amazon-kinesis

我正在尝试将 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);
    }
}

1 个答案:

答案 0 :(得分:1)

由于要将表单数据发送到服务器,您需要将 Axios 调用中的 Content-Type 标头更改为 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 )