Cloudinary 在生产中显示 JSON 错误

问题描述 投票:0回答:1

我在我的 nextjs 项目中使用这个 cloudinary 函数

import { v2 as cloudinary, UploadApiResponse } from 'cloudinary'
import dotenv from 'dotenv'

 dotenv.config()

const cloudinaryConfig = {
cloud_name: process.env.CloudName as string,
api_key: process.env.CloudapiKey as string,
api_secret: process.env.CloudapiSecret as string,
}

cloudinary.config(cloudinaryConfig)

export default async function uploadPDFtoCloud(
pdfFile: string,
): Promise<string> {
try {
const result: UploadApiResponse = await cloudinary.uploader.upload(
  pdfFile,
  {
    folder: 'file_doc_pdf',
    resource_type: 'raw',
    type: 'authenticated',
  },
)
return result.secure_url as string
} catch (error) {
 console.error('Error Uploading file:', error)
 throw new Error('Failed to upload PDF: ')
}
}

问题是这个函数在开发中正常工作并返回安全url,但是在运行 npm run build 来测试生产时我遇到了

Error Uploading file: {
message: `Server return invalid JSON response. Status Code 500. SyntaxError: Unexpected token 
'<', "<!DOCTYPE "... is not valid JSON`,     
name: 'Error',
http_code: 500

虽然构建仍在运行,并且每次运行应用程序时测试该函数,我都会遇到相同的错误,我检查了环境变量,因为所有变量都正确,但经过一些测试后,错误在此代码行触发

const result: UploadApiResponse = await cloudinary.uploader.upload(
  pdfFile,
  {
    folder: 'file_doc_pdf',
    resource_type: 'raw',
    type: 'authenticated',
  },
)

那么,可能是什么问题导致了生产中出现此错误,而为什么在开发中却没有!?

node.js typescript next.js cloudinary dev-to-production
1个回答
0
投票

您应该(根据您的情况)将文件上传为二进制文件:

//modify code below if needed 
const pdfFile = req.file.buffer.toString('base64');
console.log('pdfFile: ', pdfFile)

您遇到错误

500
,因为服务器无法处理您的 pdf。问题不是云里雾里的,问题实际上是你如何获取pdf文件。你的代码的其他部分似乎没问题。

   //mostly probably, you need to indicate base64 type of file 
   cloudinary.uploader.upload(`data:${req.file.mimetype};base64,${pdfFile}`{
            folder: 'file_doc_pdf',
            resource_type: 'raw',
            type: 'authenticated',
   },
© www.soinside.com 2019 - 2024. All rights reserved.