I am using a post request in Node.js to post an image using Axios post request, API is working fine is Postman and giving response but not working with front-end interface in browser
PS: I am using var cors = require("cors"); app.use(cors());
{message: 'Request failed with status code 405', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
Nodejs:
const client = new vision.ImageAnnotatorClient(config, clientOptions);
app.post("/images", upload.single("file"), function (req, res, next) {
// Website you wish to allow to connect
res.setHeader("Access-Control-Allow-Origin", "*");
// Request methods you wish to allow
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
// Request headers you wish to allow
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type"
);
client
.textDetection(req.file.path)
.then((results) => {
res.send(results);
})
.catch((err) => {
res.status(400).send(err);
});
});
app.use(serveStatic(path.join(__dirname, "public")));
const server = app.listen(port);
console.log(`${pjson.name} running => port ${server.address().port}`);
HTML
<form role="form" class="form" onsubmit="return false;">
<div class="form-group">
<label for="file">File</label>
<input id="file" type="file" class="form-control" accept=".JPG,.jpg,.jpeg,.gif,.png" />
</div>
<button id="text_detect" type="button" class="btn btn-primary">
Get Text
</button>
</form>
document.getElementById('text_detect').onclick = function () {
output.innerHTML = '';
const data = new FormData();
data.append('file', document.getElementById('file').files[0]);
axios.post('/images', data, { headers: { 'Content-Type': 'multipart/form-data' } }).then(
function (result) {
const properties = result.data[0].fullTextAnnotation;
console.log(properties);
}
)
.catch(function (err) {
console.log(err);
})
}