😉

【ログイン機能】Nuxt+axiosでLaravel APIからJSON取得したい

2021/06/06に公開

nuxtとlaravel apiの連携テストとして、Nuxt+axiosでLaravel APIからJSON取得したい

nuxt側

<template><h2>Result</h2>
      {{ this.message }}</template>


<script>
import Header from "@/components/header.vue";
import axios from 'axios'

export default {
  components: {
    Header,
  },
  data() {
    return {
      message: '',
    }
  },
  mounted () {
  axios.get('http://localhost:8000/api/test')
    .then((res) => {
      console.log(res.data)
      this.message = res.data
    })
    .catch((error) => {
      console.log(error)
    })
  }
};
</script>

laravel側
api.php

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
//追記
Route::get('test', function() {
    return response()->json(['name' => '山田太郎', 'gender' => '男','mail' => 'yamada@test.com']);
});

エラー発生

Access to XMLHttpRequest at 'http://localhost:8081' from origin 'http://localhost:8080' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

解決

Nginx設定に追記
default.conf

server {
    listen 80;
    root  /var/www/html/src/public;
    index index.php index.html index.htm;
    index index.html;
    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;
    //追記
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods "POST, GET, OPTIONS";
    add_header Access-Control-Allow-Headers "Origin, Authorization, Accept";
    add_header Access-Control-Allow-Credentials true;

無事取得値を表示できた

おまけ

原因がapiにあるかどうかを確かめるためにpostmanおすすめですmm
https://www.postman.com/

参照

https://qiita.com/dyoshikawa/items/c8b09cde728388c8feec#nginxで設定する場合

https://qiita.com/att55/items/2154a8aad8bf1409db2b

Discussion