現在フロントのHTMLからAPIを叩いてメールを送信しようとしています。
しかし、送信ボタンを押すと下記のようなエラーがコンソールに出力されます
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
このエラーをググったところ今いるURLから他のURLにリクエストを送ることができないようになっていると書かれてありました
そのためこれを回避するために下記のようのコードを書いたのですが、どうもエラーが解消されません。
どのように書いたらAPIを叩けるのか教えていただきたいです。
JS
const button = document.getElementById("button"); button.addEventListener("click", function(e) { e.preventDefault(); const name = document.getElementById('name').value; const subName = document.getElementById('subName').value; const companyName = document.getElementById('companyName').value; const pref_name = document.getElementById('pref_name').value; const location = document.getElementById('location').value; const companyLocation = document.getElementById('companyLocation').value; const tellNumber = document.getElementById('tellNumber').value; const mailAddress = document.getElementById('mailAddress').value; const question = document.getElementById('question').value; function sendmail(subject, body) { return fetch('MY-API', { method: 'POST', mode: 'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ subject, body }) }).then(onLoadFunc); } sendmail(name,subName,companyName,pref_name,location,companyLocation,tellNumber,mailAddress,question); });
まだ回答がついていません
会員登録して回答してみよう