Google Vision API TEXT_DETECTION请求报400错误,寻求解决方法
Hey there! Let's figure out why your Google Vision API request is throwing a 400 error. I've spotted a few key issues in your code and workflow—let's break them down step by step:
1. Fix the Typo in imageContext
This is the most likely culprit! You have a spelling mistake in the imageContext field: langaugeHints should be languageHints (note the missing 'u'). The API doesn't recognize the misspelled field, which triggers a bad request error.
2. Ensure Proper Base64 Encoding
Make sure your Base64-encoded image content doesn't include any prefixes like data:image/png;base64,. The Vision API expects only the raw Base64 string. For example, if you're using FileReader to encode the image, strip that prefix first:
// Example of cleaning up the Base64 string const base64Data = data.split(',')[1]; // Removes the "data:image/..." prefix
3. Add the Required Content-Type Header
Your fetch request is missing the Content-Type header, which tells the API you're sending JSON data. Without this, the API might fail to parse your request body correctly.
4. Verify Your API Key & API Enablement
- Double-check that your API key is valid and hasn't expired.
- Ensure the Google Vision API is enabled in your Google Cloud Console project (it's disabled by default for new projects).
Corrected Full Code Example
Here's your code with all the fixes applied:
const endPoint = `https://vision.googleapis.com/v1/images:annotate?key=${config.api_key}`; fetch(endPoint, { method: "POST", headers: { "Content-Type": "application/json" // Add this critical header }, body: JSON.stringify({ requests: [ { image: { content: base64Data // Use the cleaned Base64 string here }, features: [ { type: "TEXT_DETECTION" } ], imageContext: { languageHints: ["en"] // Fixed the spelling error here } } ] }) }) .then(response => { if (!response.ok) { return response.json().then(err => { throw err; }); } return response.json(); }) .then(data => console.log("Detection result:", data)) .catch(error => console.error("Error details:", error));
If you still get a 400 error after these fixes, check the response body for detailed error messages—it will usually spell out exactly what's wrong (like invalid Base64, missing permissions, etc.).
内容的提问来源于stack exchange,提问作者abhiwan

