LoginSignup
17
19

More than 1 year has passed since last update.

TexTraの翻訳 APIをJavaScriptだけで取得する

Last updated at Posted at 2022-08-27

Web API の JavaScript での取得方法について の質問があったので作ってみました。

See the Pen TexTra 翻訳 Demo by John Doe (@04) on CodePen.

async function handle(e) {
  name = "extra";
  key = "5b37d68901799f71e8937f26add0fafd06309732b";
  secret = "71d1b17cfdc7e26e6232a9a750c038d2";
  text = e.target.value;

  const oauth = OAuth({
    consumer: { key, secret },
    signature_method: "HMAC-SHA1",
    hash_function(base_string, key) {
      return CryptoJS.HmacSHA1(base_string, key).toString(CryptoJS.enc.Base64);
    }
  });

  const options = {
    url: "https://mt-auto-minhon-mlt.ucri.jgn-x.jp/api/mt/generalNT_en_ja/",
    method: "POST",
    data: { text, name, key, type: "json" }
  };

  const cors_support = "https://corsproxy.io/?";
  const res = await fetch(cors_support + options.url, {
    method: options.method,
    body: new URLSearchParams(options.data),
    headers: oauth.toHeader(oauth.authorize(options))
  }).then((r) => r.json());
  document.all.output.value = res.resultset.result.text;
}

Python

Pythonでもpipで簡単にインストールできるようにしてみました。

pip install textra

trans 'I am a cat.'
私は猫です。
17
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
19