前提
node.jsでGoogleのspeech-to-text-APIを使用しようとしています。
ajaxのpost通信ができなくて困っています。
実現したいこと
ajaxを使ってAPIにデータを送りたい
発生している問題・エラーメッセージ
Speech API Error:{"readyState":0,"status":0,"statusText":"error"} Error: Cross origin null forbidden at dispatchError (/Users/taichitanaka/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:63:19) at Object.validCORSHeaders (/Users/taichitanaka/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:75:5) at receiveResponse (/Users/taichitanaka/node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js:794:19) at Request.<anonymous> (/Users/taichitanaka/node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js:658:43) at Request.emit (node:events:513:28) at Request._processResponse (/Users/taichitanaka/node_modules/jsdom/lib/jsdom/living/helpers/http-request.js:228:12) at ClientRequest.<anonymous> (/Users/taichitanaka/node_modules/jsdom/lib/jsdom/living/helpers/http-request.js:101:12) at Object.onceWrapper (node:events:628:26) at ClientRequest.emit (node:events:525:35)
該当のソースコード
javascript
1const jsdom = require('jsdom'); 2const { JSDOM } = jsdom; 3const dom = new JSDOM(`<html><body><div id="aaa">AAA<div></body></html>`); 4const { document } = dom.window; 5const jquery = require('jquery'); 6const $ = jquery(dom.window); 7 8var key = "*********************"; 9 10load_file(); 11function load_file() { 12 var json = { 13 "config": { 14 "encoding": "LINEAR16", 15 "sample_rate": 44100, 16 "language_code": "ja_JP" 17 }, 18 "audio": { 19 "content": "unko.wav" 20 } 21 }; 22 voice_recognition(json); 23} 24 25function voice_recognition(json){ 26 $.ajax({ 27 type: 'POST', 28 url: 'https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=' + key, 29 data: JSON.stringify(json), 30 dataType:'json', 31 contentType: 'application/json' 32 }).done(function(data) { 33 console.log(data.results[0].alternatives[0].transcript); 34 }).fail(function(error) { 35 console.log("Speech API Error:" + JSON.stringify(error)); 36 }); 37}
試したこと
https://eniel.blog.fc2.com/blog-entry-479.html
上記のサイトで書かれている通りエラーメッセージを出しているメソッドの一番上にreturn trueを入れ強制的にtrueを返すようにしました。
結果:エラー自体は消えました結果が帰ってこないので正常に動作していないと思います。
return trueを入れた場所↓
/Users/***/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js 内の58行目
JavaScript
1function dispatchError(xhr) { 2 return true; 3 const errMessage = xhr.properties.error; 4 requestErrorSteps(xhr, "error", DOMException.create(xhr._globalObject, [errMessage, "NetworkError"])); 5 6 if (xhr._ownerDocument) { 7 const error = new Error(errMessage); 8 error.type = "XMLHttpRequest"; // TODO this should become "resource loading" when XHR goes through resource loader 9 10 xhr._ownerDocument._defaultView._virtualConsole.emit("jsdomError", error); 11 } 12}
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答1件
あなたの回答
tips
プレビュー