javascript - POST请求responseType“数组缓冲区”是否可行?
问题描述
我制作了一个将返回图像的api。起初我在 get 方法请求上尝试过它并且它可以工作,但出于安全原因,我需要让它发布方法,但 post 不像我的 get 方法那样工作。您是否认为 responseType 仅在 get 方法中可用,因为它不适用于我的 post 方法?
这是我使用有效的 get 方法的代码:
前端:
export const getImageFile = async (imageName) => {
try {
const { data } = await axios.get(`${apiUrl}/image/${imageName}`,{
responseType: "arraybuffer",
});
const image = new Buffer.from(data, "binary").toString("base64");
return `data:image/png;base64, ${image}`;
} catch (err) {
alert("File not found.");
}
};
后端(php symfony):
/**
* @Route("/api/graph/image/{imageName}", methods={"GET"}, name="get- image-graph")
*/
public function getImage($imageName)
{
try {
$file = $this->parameterBag->get('kernel.project_dir').'/public/graphImage/graphs/'.$imageName;
$response = new BinaryFileResponse($file);
return $response;
} catch (\Exception $e) {
return $this->json(['error' => 'File not found'], JsonResponse::HTTP_NOT_FOUND);
}
}
当我使用不起作用的 POST 方法时,这是我的代码:
前端:
export const getImageFile = async (imageName) => {
try {
const { data } = await axios.post(`${apiUrl}/image`,{
responseType: "arraybuffer",
"imageName": imageName,
});
const image = new Buffer.from(data, "binary").toString("base64");
return `data:image/png;base64, ${image}`;
} catch (err) {
alert("File not found.");
}
};`
backend:
```php
/**
* @Route("/api/graph/image", methods={"POST"}, name="get-image-
graph")
*/
public function getImage(Request $request)
{
try {
$content = json_decode($request->getContent(), true);
$imageName = $content["imageName"];
$file = $this->parameterBag->get('kernel.project_dir')
.'/public/graphImage/graphs/'.$imageName;
$response = new BinaryFileResponse($file);
return $response;
} catch (\Exception $e) {
return $this->json(['error' => 'File not found'],
JsonResponse::HTTP_NOT_FOUND);
}
}`
解决方案
从文档中,
axios.post(url, data, config)
您的发帖请求:
const { data } = await axios.post(`${apiUrl}/image`,{
responseType: "arraybuffer",
"imageName": imageName,
});
看来您混合了数据和配置。所以你的帖子请求应该是
const {data} = await axios.post(
`${apiUrl}/image`,
{
"imageName": imageName,
},
{
responseType: "arraybuffer"
}
);
// In server side php,you access it like
$image = $_POST["imageName"];
如果您想将其作为 json 发送,请在配置中使用标头
{
responseType: "arraybuffer",
headers: {'Content-Type': 'application/json'}
}
推荐阅读
- javascript - 有什么方法可以仅通过客户端 javascript 连接到 gsheets api?
- c++ - 对象的构造函数和析构函数
- python - 如何从字典中删除一个值?
- xpath - XPath 返回包含字符串值的树中所有唯一元素的列表
- sql - 如何在 SQL 中使用数据透视(不是作为 DataFrame 分组运算符)?
- c++ - C++ 预期的嵌套名称说明符
- javascript - vForm 错误无法在用户的表单中显示
- google-analytics - 检索一个产品的多个 Google Analytics 行是产品范围的 customDimension 值在 Google Big Query 中不同
- python - 如何让用户创建任意数量的字典
- java - 如果数组具有重复的元素,则在Java中进行2路合并