0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

フロントエンドでCookieが送れない問題の解決メモ

Posted at

はじめに

フロントエンドはreact、バックエンドにrailsを用いてアプリ開発を行っていたのですが、POSTリクエストを送信したらエラーが返ってきたので備忘録としてまとめます。

状況

フロントエンドからPOSTを行ったところ、リクエストヘッドにcookieが含まれておらずそれが原因でエラーが起きている。

ButtonAppBar.jsx
    const response=await fetch('http://localhost:3000/user_books',{
      method:'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',  // JSON形式で送信することを指定
      },
      body:JSON.stringify({
        isbn:bookinfo.isbn
      })
    })

しかし、curlでリクエストを行うと正常に処理を完了できたため、フロントエンドの書き方が原因でコードをきちんと送ることができていないことが判明しました。

curl -i -b cookie.txt -X POST http://localhost:3000/user_books \3000/user_books \
  -H "Content-Type: application/json" \
  -d '{"isbn": "9784022516121"}'
HTTP/1.1 204 No Content
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 0
X-Content-Type-Options: nosniff
X-Download-Options: noopen
X-Permitted-Cross-Domain-Policies: none
Referrer-Policy: strict-origin-when-cross-origin
Cache-Control: no-cache
X-Request-Id: c96cb7ff-40ab-494c-ba83-dfcc84370ff5
X-Runtime: 0.544018
Server-Timing: start_processing.action_controller;dur=0.13, sql.active_record;dur=76.34, instantiation.active_record;dur=0.41, process_action.action_controller;dur=541.72
vary: Origin

原因

リクエストが成功しているコードと見比べると

ButtonAppBar.jsx
http://localhost:3000

ではなく

AwardTable.jsx
http://127.0.0.1:3000

に対してリクエストを行っていることが判明しました。そこでButtonAppBar.jsxでも

ButtonAppBar.jsx
http://127.0.0.1:3000

のようにしたところ、リクエストが成功しました!

結論

結論として、
http://127.0.0.1:3000http://localhost:3000 はおなじオリジンであると考えていましたが、コンピュータは異なるオリジンとして認識していました。
そのため、ログイン時にhttp://127.0.0.1:3000 対してリクエストを行い発行したcookieをhttp://localhost:3000 では使用することができず、リクエストにcookieが含まれておらずエラーが起きていました。
今後ログイン時に送ったリクエストと同じオリジンに対して、リクエストを送り続けるように統一することでエラーを防ぐことができます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?