I'm trying to start an archive in a session embedded in web page using javascript to make the opentok REST API calls. My JS looks like this:
var json_web_token = {
"iss": apiKey,
"ist": "project",
"iat": Date.now(),
"exp": Date.now()+180, // 3 minute expiry, max is 5...
"jti": token
}
//JSON.parse()
var archivedata = {
"sessionId" : sessionId,
"name" : archiveName,
"resolution" : "1280x720",
"layout": "pip"
}
fetch('https://api.opentok.com/v2/project/' + apiKey + '/archive', {
method: 'POST',
mode: 'no-cors',
body: JSON.stringify(archivedata),
headers: new Headers({
'Content-Type': 'application/json',
'X-OPENTOK-AUTH': JSON.stringify(json_web_token),
})
})
.then(response => response.json())
.then(data => {
console.log(data) // Prints result from `response.json()`
})
.catch(error => console.error(error));
However, I get the following console error: POST https://api.opentok.com/v2/project/XXXXXXXX/archive 415 (Unsupported Media Type)
Any ideas?
TokBox Developer Evangelist here.
When generating the JWT token, you need use a JWT library and sign the token using your TokBox API Secret. Since you're using JavaScript, you can use the jsonwebtoken package. Your code for signing the code would then look like this:
const jwt = require('jsonwebtoken'); // importing the library
const apiKey = '';
const apiSecret = '';
const currentTime = Math.floor(new Date()/1000);
const token = jwt.sign({
"iss": apiKey,
"ist": "project",
"iat": currentTime,
"exp": currentTime + 180, // maximum is 300
"jti": "jwt_nonce",
}, apiSecret);
Please note that you should not generate the JWT token on the client side because you would then expose the API Secret. Anyone with your API Key and Secret would then be able to use the OpenTok API as you.
Alternatively, you could use the OpenTok Server SDKs that let you create OpenTok sessions, generate tokens, work with OpenTok archiving, broadcasting, SIP, and more. You wouldn't have to worry about generating the JWT token because the server SDK would do that on your behalf.
Resources: