java - 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);
}
}
解决方案
由于您想将表单数据发送到服务器,因此您需要将Content-Type
Axios 调用中的标头更改为multipart/form-data
. 这有助于服务器了解客户端发送的资源类型。
在服务器端,您需要读取此表单数据。我可以想到以下两种方法来做到这一点
- 用于
@RequestParam
读取单个表单键。例如,如果我的表单数据包含一个名为 的键Foo
,我会在服务器端读取它,因为
@PostMapping(value = "/form-data")
public void readFormData( @RequestParam(value = "Foo") String foo )
- 用于
@RequestBody
将表单数据映射到MultiValueMap
可以像法线贴图一样读取的数据。这是相同的代码片段
@PostMapping(value = "/form-data")
public void readFormData( @RequestBody MultiValueMap<String,String> formData )
推荐阅读
- javascript - 提取给定日期范围的 JSON 总和?
- python-3.x - Trello API / Python - 无法为卡片设置自定义字段值
- java - 在 Java 中读取巨大的 Json 响应时内存不足
- java - 如何在实时服务器上部署 Spring Boot 应用程序并与 mysql 建立数据库连接
- powershell - gvim 8.2 不会粘贴在 powershell 中的 Windows 10 上
- java - 一个 String 对象加上另一个 String,结果取决于两个 String 对象的参数
- python - 尝试在 MacBook 中将 Pygal 导入 Atom
- java - 为soap xml字符串制作java类
- ios - 如何重新安装/重置 lldb?
- r - 我尝试更改 ggplot 中的字体但收到错误“从 .ttf 文件中提取 .afm 文件...”,为什么?