Hello, I’m working on my first custom Twitch Extension and have been following along with the Extension 101 Tutorial Series ( JSON Web Tokens (JWT) | Twitch Developers ) while making my extension. I’m having a hard time figuring out a CORS issue which is shown below. Prior to, allow me to briefly explain the project:
In my extension, one of four buttons are pressed calling a JS function which runs:
$.ajax({
type: 'POST',
url: location.protocol + '//localhost:3000/words',
data: JSON.stringify( {term: word, difficulty: difficulty_level} ),
contentType: 'application/json',
headers: { 'Authorization': 'Bearer ' + token }
});
On my backend JS file the following related code is executed:
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST');
res.setHeader('Access-Control-Allow-Origin', '*');
next();
});
//Secret
const key = "omitted for obvious reasons";
const secret = Buffer.from( key, 'base64');
//JWT - Bearer Prefix
const bearerPrefix = 'Bearer ';
function verifyAndDecode(header) {
if (header.startsWith(bearerPrefix)) {
try {
const token = header.substring(bearerPrefix.length);
return jsonwebtoken.verify(token, secret, { algorithms: ['HS256'] });
}
catch (e) {
return console.log('Invalid JWT');
}
}
}
//Mongoose - Model
var Word = mongoose.model("Word", {
userID: String,
term: String,
difficulty: String,
});
//Express - POST Route
app.post("/words", (req, res) => {
const payload = verifyAndDecode(req.headers.authorization);
const { channel_id: channelId, opaque_user_id: opaqueUserId } = payload;
//console.log(req.body)
var newWord = new Word({
userID: payload.opaque_user_id,
term: req.body.term,
difficulty: req.body.difficulty});
newWord.save(function (err) {
if (err) handleError( err );
})
});
The error received when pressing one of my buttons is:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/words. (Reason: CORS request did not succeed). Status code: (null).
Additionally, I get the same error whenever trying to get the words in my live configuration.
$.ajax({
type: 'GET',
url: location.protocol + '//localhost:3000/words',
success: function(response) {
var trHTML = '';
$.each(response, function(i, item) {
trHTML += '<tr><th>' + item.term + ' | ' + item.difficulty + '</td></tr>';
});
$('#word-container').append(trHTML);
}
});
Backend code is as follows:
app.get('/words', (req, res) => {
Word.find({}).then(function(words) {
res.send(words);
});
});
Is there something wrong with my code? Is the protocol location not set up correctly?