LoginSignup
1
0
はじめての記事投稿

CORSエラーと疑う前にリクエストボディの形式を再確認しよう

Posted at

概要

Next.jsからバックエンド(laravel)に対してユーザー登録を行おうとした際に
CORSエラーが発生しました。
最終的にCORSエラーではなく、初歩的なミスによるものでした。。。
解決までに時間が掛かってしまった為、記事として記載しました。

まず結論

Next.jsでPOSTリクエストを送る際の、bodyの形式が誤っていました・・・

// NG
const data = {
	lastName,
	firstName,
	age,
	gender
}

// OK!
const data = {
	last_name: lastName,
	first_name: firstName,
	age: age,
	gender: gender
}

なぜハマったのか

Next.jsからリクエストを送った際に返却されたエラーメッセージが
'Access-Control-Allow-Origin'ヘッダーが存在しない旨の内容であったため
CORSの設定が原因だと思い込んでしまったため。

NextErrorMessage.png

create:1 Access to fetch at 'http://localhost:3001/' 
(redirected from 'http://localhost:8080/api/users') from origin 'http://localhost:3001' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
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.

最後に

自分への戒めと今後同じような内容でハマった人の為に記事を書きました。

1
0
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
1
0