I’m trying to move a client side fetch to a server side fetch in a nextjs app. The client side fetch works, but exposes the API secret key. Thus the need to move the call to my server. However, when i move the fetch to my server, the API always responds with File Type not detected. I even tried adding the ‘filetype’ parameter to force it, but no luck there either. I’ve tried a million things but cannot figure out why this doesn’t work.
Client side fetch:
const url = '/api/parse-image'
const formData = new FormData()
formData.append('file', file)
formData.append("language", "eng")
formData.append("scale", "True")
formData.append("OCREngine", "2")
formData.append("filetype", "JPG")
const params: RequestInit = {
method: 'POST',
mode: 'cors',
headers: {
content: 'multipart/form-data',
'Access-Control-Allow-Origin': '*',
},
body: formData,
}
return fetch(url, params)
.then(response => {
doneCallback()
return response.json()
})
Server API fetch:
import fetch from 'isomorphic-unfetch'
import { NextApiRequest, NextApiResponse } from 'next'
const { OCR_SECRET } = process.env
if (!OCR_SECRET) {
throw new Error(
'Please define the OCR_SECRET environment variable inside .env.local'
)
}
export default async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const params: RequestInit = {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'multipart/form-data',
'Access-Control-Allow-Origin': '*',
apikey: OCR_SECRET,
},
body: req.body,
}
await fetch('https://api8.ocr.space/parse/image', params)
.then(r => r.json())
.then(json => res.json(json))
}
}