文件上传:req.files 未定义。

时间:2021-08-12 04:04:09

标签: javascript node.js typescript express file-upload

我正在使用名为 express-fileupload 的库进行文件处理中间件。但是当我执行 console.log(req.files) 时,它显示未定义。我检查了 Chrome 开发工具中的请求头,它显示为 img/png,但是 Express 说它是未定义的。

以下是我的客户端代码:

public static async upload(data: Upload){
      const track = data.track
      const artwork = data.artwork
      if(track && artwork){
          try{
              await Req.upload("/api/u/music/upload", track)
              await Req.upload("api/u/music/upload", artwork)
          }catch(err){
              console.log(err)
          }
      }
}

/*req class*/

export class Req {
    public static async upload(url: string, file: File|null|undefined){
      const response = await fetch(url, { // Your POST endpoint
        method: 'POST',
        headers: {
          // Content-Type may need to be completely **omitted**
          // or you may need something
          "CSRF-Token": <string>Cookies.get("XSRF-TOKEN"),
        },
        body: file // This is your file object
      })
      return await response.json()
    }
}

在我的服务器端:

app.use(cors())
app.use(bodyParser.urlencoded({extended : true, limit: "100mb"}));
app.use(bodyParser.json({limit: '100mb'}));
app.use(express.static(path.join('build')))
app.use(cookieParser())
app.use(fileUpload())
app.use(csrf({cookie: true}))

export const uploadMusic = async (req: Request, res: Response)=>{
    console.log(req.files) //undefined
    res.send({"upload_status": "ok"})
}

0 个答案:

没有答案