javascript - 带有json的后请求,如何访问正文?
问题描述
我试图了解如何使用 json 信息在 spring 中处理 post-requests。但我有一种感觉,我错过了一些东西。我想我不应该在发布请求中使用 RequestParam,但我不明白如何访问正文值。
后端
@CrossOrigin(origins = "http://localhost:3000")
@PostMapping(path = "api/delete", consumes = "application/json", produces = "application/json")
@ResponseBody
public String delete(@RequestParam("filename") String filename) throws IOException {
String filePath = imageFolder + filename;
File file = new File(filePath);
logger.info(filePath);
if(file.delete())
{
return "{\"success\":1}";
}
else
{
return "{\"fail\":1}";
}
}
前端
const deleteImage = () => {
const re = /images\/(.+)$/;
const filePath = imageUrl.match(re);
const url = `http://localhost:8080/api/delete/`
const data = {filename:filePath}
const options = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: data
};
fetch(url, options);
};
解决方案
添加 RequestBody 而不是 RequestParam。
public String delete(@RequestBody String filename) throws IOException {}
更多@RequestBody示例
RequestBody和 RequestParam 之间的区别。
推荐阅读
- xslt - select multiple attribute values in xslt
- flutter - 如何将 Flutter_App_link 分享到 facebook、twitter、instagram 等社交媒体?
- python-3.x - O如何使用python从图像的特定区域提取文本?
- node.js - 将大量数据保存到mongodb
- android - 如何在我的 Anko 布局中设置 topMargin
- c++ - 使用 C++ 从非指定符号中清除 CSV 文件
- python - 如何在python中将任意长度的位串写入二进制文件
- php - 为什么我的 eloquent 查询在以后使用时会被覆盖?
- kubernetes - ISTIO sidecar 使用 Jaegar 进行分布式跟踪
- python - Python - 命令行参数提取为字符串 ImportError