😉
【ログイン機能】Nuxt+axiosでLaravel APIからJSON取得したい
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
参照
Discussion