Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

javascript - API authorization 401 problem (only JS via browsers) - how to fix?

I need to get (any) OK-response from Yandex SpeechKit.API. I got API-KEY (valid) and successfully used it and received responses via NodeJS and even GitBash (see links to screens below). But browsers show me 401: enter image description here There're rules for API requests: docs. My JS code for browsers:

let api_key = '*********c_Ujs9scAhJVVZOs2xjnbvevqj6OFFm';
let params = new URLSearchParams();

const text = 'Привет!';
params.append('text', text);
params.append('voice', 'jane');
params.append('emotion', 'good');
params.append('lang', 'ru-RU');
params.append('speed', '1.0');
params.append('format', 'oggopus');

const fetchButton = document.getElementById("fetchButton");

fetchButton.onclick = () => {

  fetch('https://tts.api.cloud.yandex.net/speech/v1/tts:synthesize', {
    method: 'POST',
    body: params,
    mode: "no-cors",
    headers: {
      //'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': 'Api-Key ' + api_key,
    },
  }).then((res) => {
    console.log(res);
  }).catch((err) => {
    console.error(`!!! + ${err} + !!!!!!!!`)
  });

}

There're code examples for Node and Bash:

[nodeJS code][3] gitBash code

question from:https://stackoverflow.com/questions/65892706/api-authorization-401-problem-only-js-via-browsers-how-to-fix

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You said:

mode: "no-cors",            //required

… this means "I am making a cross-origin request, but I am not doing anything that requires the server grant me permission with CORS so instead of throwing errors, fail silently".

You also said:

'Authorization': 'Api-Key ' + api_key,

Setting this header requires permission from CORS. Since you are in no-cors mode it automatically and silently fails to be set.

Since you didn't set the authorisation key, you get a 401 Unauthorised response from the server.


You can't use no-cors mode here, even if you have a comment saying it is required.

There is some further reading on CORS you may find useful. Note that since the service you are using requires an API key and imposes limits, it likely isn't intended for use from a browser and you should implement a server-side solution instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...