実現したいこと
SpringBootで作成したWebAPIをブラウザのJavaScriptから呼び出しPOST、GET、PUT、DELETEの各処理を実行する。
前提
SpringBootで作成したWebAPIの呼出しは、curlコマンドとpostmanで動作確認しています。
画面でfetchで呼び出した際にCORSエラーが発生します。
環境
WSL2
Description: Ubuntu 20.04.6 LTS
クライアントもサーバ側も同一のWSL上で動作しています。
クライアント: http://localhost:3000
サーバ: http://localhost:8080
発生している問題・エラーメッセージ
発生した際のエラーは以下のようなエラーです。
ブラウザ側
text
1Access to fetch at 'http://localhost:8080/files/uploadfiles/json' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
サーバ側
text
1Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'text/plain;charset=UTF-8' is not supported]
該当のソースコード
ブラウザ側はReactで作成していますが、以下のようなボタンをクリックするだけの処理です。
(まだ実装の調査中)
javascript
1 function WebApiPost(){ 2 let postData = { 3 "title": "Baby", 4 "category": "Pops", 5 "release_date": "2020-01-07" 6 }; 7 8 const uri = "http://localhost:8080/files/uploadfiles/json"; 9 const params = { 10 method:"POST", 11 header:{ 12 "Content-Type": "application/json", 13 //"Connection": "keep-alive" 14 }, 15 body: JSON.stringify(postData), 16 //mode: "cors", 17 //withCredentials: true, 18 //crossorigin: true 19 }; 20 fetch(uri, params).then((response) => { 21 console.dir(response); 22 return response; 23 }).then((result) => { 24 if(result.ok) { 25 return result.json(); 26 }else{ 27 throw new Error("リクエスト失敗"); 28 } 29 }).then((json) =>{ 30 console.log(json); 31 }).catch((error) => { 32 console.warn(error); 33 }) 34 } 35 36// 呼び出し側 37<button onClick={WebApiPost}>bbbbb</button>
WebAPI側
java
1@RequestMapping("/files") 2@RestController 3//@CrossOrigin(origins = "http://localhost:3000") 4public class WebApiFileUpload { 5 6 7 @PostMapping("/uploadfiles/json") 8 //@CrossOrigin(origins = "http://localhost:3000") 9 public ResponseEntity<FileUploadResponse> jsonUploadFiles(@RequestBody HashMap body) { 10 11 System.out.println(body); 12 var ret = new FileUploadResponse(); 13 ret.setFileName("hogehoge"); 14 ret.setSize(0); 15 ret.setDownloadUri("/downloadfile"); 16 17 var headers = new HttpHeaders(); 18 var response = new ResponseEntity<FileUploadResponse>(ret, HttpStatus.OK); 19 return response; 20 21 } 22} 23
その後CROSエラーの解決の為、CrossOriginを追加してみたところ、エラー内容が変わりましたがアクセスはできません。
(Java側のコメントアウトされている部分)
ブラウザ側
App.js:55 POST http://localhost:8080/files/uploadfiles/json 415
サーバ側
text
1Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'text/plain;charset=UTF-8' is not supported]
質問内容
- CORSエラーの解決方法としてはCrossOriginの属性で問題ない?
- サーバ側でtext/plainとなっているが、クライアント側のHeaderでContent-Typeの指定方法が間違っているかその他の理由があるのか?
- CORSエラーの内容についてはとりあえずで調査しているのでお勧めの本やHPがあればご紹介頂きたいです。
最後に
最後まで読んで頂きありがとうございます。
どなたかわかる方がいらっしゃれば、ご回答よろしくお願いいたします。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。