I am sending a base64 string from my mobile app to my Express server via POST
request. The image is sent to a Google client endpoint, but it is returning an error: Provided image is not valid
code: 400, 0|index | errors: [ 0|index | { 0|index | message: 'Provided image is not valid.', 0|index | domain: 'global', 0|index | reason: 'badRequest' 0|index | } 0|index | ]
I think it has to do with the body-parser
breaking my stringified body from client side to server endpoint.
On the client:
const body = typeof data === 'string' ? data : JSON.stringify(data); // data is base64 string;
const response = await fetch(path, {
method,
body,
headers: {
...headers,
},
});
Here is a gist of base64 from the client: https://gist.github.com/lucksp/0a831684c34271424309096172ccb79a#file-clientbase64-js
You can see the highlighted string includes text of: CZjs+EJ+/+I
.
Now, here is the log of the same asset on the server:
You can see the highlighted string includes text of CZjs EJ / IC
instead. the +
's have been stripped.
Here is my Express server code.
const app = express();
app.use(bodyParser.json({ limit: '20mb' }));
app.use(
bodyParser.urlencoded({
limit: '20mb',
extended: true,
parameterLimit: 50000,
})
);
app.use(bodyParser.text({ limit: '200mb' }));
async function callPrediction({
endpoint,
data,
}: {
endpoint?: string | null;
data: string;
}) {
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
const client = await auth.getClient();
const body = JSON.stringify({
instances: [
{
content: data,
},
],
parameters: {
confidenceThreshold: 0.5,
maxPredictions: 5,
},
});
const res = await client.request({
method: 'POST',
url,
body,
headers: { 'Content-Type': 'application/json' },
});
return res;
};
app.post('/verify', async (req, res) => {
const results = await callPrediction({
endpoint: endpoints[0].name,
data: req.body, // comes in as a stringified JSON. Also fails if parsing here.
});
}
Am I doing something wrong with bodyParser
or is it the base64?Am I doing something wrong with bodyParser
or is it the base64?
What's really odd is that the same base64 sent from Postman works fine.