繁体   English   中英

“字符串”JSON 类型上不存在属性“url”

[英]Property 'url' does not exist on type 'string' JSON

当我将某些内容上传到 azure blob 存储时,我正在尝试发送一些 JSON 的url 对象是req.files 当我console.log req.files ,我得到类似的东西:

[
  {
    fieldname: 'chooseFile',
    originalname: 'video.mov',
    encoding: '7bit',
    mimetype: 'video/quicktime',
    container: 'asset-afe1b5d0-cf8f-11eb-9615-13b96d691770',
    blobPath: '1623950892848-aGxhZC5tb3Y%3D.mov',
    url: 'https://cdn.example.com/item/this/that'
  }
]

如果我尝试,比如说, console.log req.files.url ,我会收到类似这样的错误:

Property 'url' does not exist on type '{ [fieldname: string]: File[]; } | File[]'.
  Property 'url' does not exist on type 'File[]'

所以我试过这个:

const filedata = JSON.stringify(req.files)
console.log(filedata)

它返回更像这样的东西:

[{"fieldname":"chooseFile","originalname":"video.mov","encoding":"7bit","mimetype":"video/quicktime","container":"path","blobPath":"item.mov","url":"https://cdn.example.net/this/path/here/there"}]

现在,如果我尝试console.log filedata.url ,我会收到如下错误:

Property 'url' does not exist on type 'string'

这里的第一个问题是req.files是一个数组,而不是一个对象。 因此,您应该访问req.files[0].url以访问req.files的第一个元素,然后获取其url属性。

第二个问题是尝试在JSON.stringify数组之后获取属性url JSON.stringify返回一个 JS 对象的字符串表示,字符串没有url属性。

因此,您最有可能的意思是console.log(req.files[0].url) ,假设您知道req.files只会有一个元素,或者您只需要第一个元素。

尽管所有评论和答案都声称这是一个数组,但在查看包的源代码后,我看到了JSON.parse 不,这不是数组。 我做的一切都是正确的。 这是一个无关的 Typescript 错误。 我通过将req的类型从express.Request更改为any来修复它。 然后req.files.url将工作得很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM