我的代码在这里。
我想使用 Nestjs 将文件上传到 Synology。 但它没有达到我的预期。
synology 在超时之前不会响应。
我的代码问题出在哪里?
https://global.download.synology.com/download/Document/Software/DeveloperGuide/Package/FileStation/All/enu/Synology_File_Station_API_Guide.pdf (FormData 不是“表单数据”)
// Service
import { HttpService } from '@nestjs/axios';
constructor(private readonly http: HttpService) {}
async uploadFile(files: File[], file_path: string) {
try {
const formData = new FormData();
for (const file of files) {
formData.append('file', file);
}
const data = await firstValueFrom(
this.http
.post(process.env.SYNOLOGY_URL, formData, {
params: {
api: 'SYNO.FileStation.Upload',
version: 2,
method: 'upload',
_sid: this.sid,
path: file_path,
create_parents: false,
overwrite: false,
},
})
.pipe(map((response) => response.data)),
);
} catch (error) {
console.error(JSON.stringify(error, null, 2));
}
}
超时响应
{
"message": "timeout of 10000ms exceeded",
"name": "AxiosError",
"stack": "AxiosError: timeout of 10000ms exceeded\n at RedirectableRequest.handleRequestTimeout (/usr/projects/backend/init_nestjs/node_modules/axios/lib/adapters/http.js:647:16)\n at RedirectableRequest.emit (node:events:518:28)\n at Timeout.<anonymous> (/usr/projects/backend/init_nestjs/node_modules/follow-redirects/index.js:210:12)\n at listOnTimeout (node:internal/timers:573:17)\n at processTimers (node:internal/timers:514:7)\n at Axios.request (/usr/projects/backend/init_nestjs/node_modules/axios/lib/core/Axios.js:45:41)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 10000,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "multipart/form-data; boundary=axios-1.6.8-boundary-KyPk5XLtcOCa_vHTRUxIf-PRY",
"User-Agent": "axios/1.6.8",
"Content-Length": "263074",
"Accept-Encoding": "gzip, compress, deflate, br"
},
"maxRedirects": 5,
"params": {
"api": "SYNO.FileStation.Upload",
"version": 2,
"method": "upload",
"_sid": "SYNOLOGY_SID"
"path": "/docker",
"create_parents": false,
"overwrite": false
},
"method": "post",
"url": "SYNOLOGY_URL/webapi/entry.cgi",
"data": {}
},
"code": "ECONNABORTED",
"status": null
}
使用 import * as FormData from 'form-data' 而不是基本的 FormData。 因为使用 formData.getHeaders()。
但是当 formData.append('file', file) 时我显示错误“source.on 不是函数”
-->
post(process.env.SYNOLOGY_URL, ...)
我肯定会先检查
SYNOLOGY_URL
是否在环境中🙃
-->
env: {}
专业提示:如果您使用
.env
文件,则必须首先将其内容加载到环境中。例如,通过 ConfigService
(您在这里没有使用)、dotenv
或类似的东西。这就是为什么在 99% 的情况下跳过 NestJS 原生配置逻辑会适得其反。
或者,再看一遍:
"url": "SYNOLOGY_URL/webapi/entry.cgi",
这是正确的网址吗?
第三次查看,你是否设置了正确的请求头?
第四次查看时,抓住
nestjs-http-promise
- 您无需与 rxjs 作斗争。