How to make the Speech API call?
Simple Express Server
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const pino = require('express-pino-logger')();
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(pino);
app.get('/api/get-speech-token', async (req, res, next) => {
res.setHeader('Content-Type', 'application/json');
const speechKey = process.env.SPEECH_KEY;
const speechRegion = process.env.SPEECH_REGION;
if (speechKey === 'paste-your-speech-key-here' || speechRegion === 'paste-your-speech-region-here') {
res.status(400).send('You forgot to add your speech key or region to the .env file.');
} else {
const headers = {
headers: {
'Ocp-Apim-Subscription-Key': speechKey,
'Content-Type': 'application/x-www-form-urlencoded'
}
};
try {
const tokenResponse = await axios.post(`https://${speechRegion}.api.cognitive.microsoft.com/sts/v1.0/issueToken`, null, headers);
res.send({ token: tokenResponse.data, region: speechRegion });
} catch (err) {
res.status(401).send('There was an error authorizing your speech key.');
}
}
});
app.listen(3001, () =>
console.log('Express server is running on localhost:3001')
);
Token Utility Function
import axios from 'axios';
import Cookie from 'universal-cookie';
export async function getTokenOrRefresh() {
const cookie = new Cookie();
const speechToken = cookie.get('speech-token');
if (speechToken === undefined) {
try {
const res = await axios.get('/api/get-speech-token');
const token = res.data.token;
const region = res.data.region;
cookie.set('speech-token', region + ':' + token, {maxAge: 540, path: '/'});
console.log('Token fetched from back-end: ' + token);
return { authToken: token, region: region };
} catch (err) {
console.log(err.response.data);
return { authToken: null, error: err.response.data };
}
} else {
console.log('Token fetched from cookie: ' + speechToken);
const idx = speechToken.indexOf(':');
return { authToken: speechToken.slice(idx + 1), region: speechToken.slice(0, idx) };
}
}
Last updated