前提·您要实现的目标
我想使用React的axios从API服务器获取json。
身份验证方法使用Laravel默认AUTH。
由于我们只想在API端登录时才返回JSON,因此我们将中间件(auth)与Laravel路由结合使用。
出现的问题·错误消息
如果您从浏览器中点击api,它将正常显示,但是如果您经过React的axios,则会出现以下错误。 401(未经授权)
It can be taken by accessing from the browser
源代码
■React.js
import axios from 'axios';
const host = window.location.protocol + '//api.' + window.location.hostname ;
const path = window.location.pathname
export const getIndex = nowId =>
axios
.get(host + '/v1/movie/' + nowId, {
headers: {
'Accept': 'application/json',
},
})
.then((results) => {
const status = results.status
if(typeof result === 'undefind'){
return status
}
const indexDatas = results.data[0]
return indexDatas
}).catch(
error => {}
);
■Laravel(API)
・ /routes/web.php
Route::get('/auth/login/{token}', 'Auth\LoginController@auth');
Route::get('/auth/logout', 'Auth\LoginController@logout');
Route::get('/v1/sidemenu', 'ChallengersController@sidemenu');
Route::group(['prefix'=>'v1', 'middleware' => ['auth']],function(){
// Movie
// =======
Route::group(['prefix'=>'movie', 'middleware' => ['cors']],function(){
Route::get('/contents', 'MovieController@contents');
Route::get('/addContents', 'MovieController@addContents');
Route::get('/{id}/getChapter', 'MovieController@getChapter');
Route::get('/{id}/getReview', 'MovieController@getReview');
Route::get('/{id}/reviewCount', 'MovieController@getReviewCount');
Route::post('/postReview', 'MovieController@postReview');
Route::get('/review/commit', 'MovieController@reviewCommit');
Route::get('/{id}', 'MovieController@detail');
Route::get('/list', 'MovieController@index');
});
// Podcast
// =======
Route::group(['prefix'=>'audio'],function(){
Route::get('/list', 'PodcastController@index');
Route::get('/{id}', 'PodcastController@detail');
});
// Lecture
Route::group(['prefix'=>'lecture'],function(){
Route::get('/', 'LecturesController@index');
Route::get('/{id}', 'LecturesController@show');
Route::get('/{id}/schedules', 'LectureSchedulesController@index');
});
});
・ /config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
此问题的解决方案是将身份验证信息提供给请求方(React的axios)的标头吗?
然后,应该在标题中放入哪种内容? 我尝试放置与下图相同的内容,但没有移动。
axios
.get(host + '/v1/movie/' + nowId, {
headers: {
'Accept': 'application/json',
'Set-Cookie': 'laravel_session=eyJpdiI6IitBVldGM0VORzFZRk1ick1IY2Z5d1E9PSIsInZhbHVlIjoiT3JPeUVHc3BSaE5vRXF0KzB3N2xXRkdXb0xwMDVvS0RZR1VQM0xmMFkySnNrS01KRHVXMTFWNVhTU1wvMTVwa3RDRmNvajVMZGhiU2t4dFEzY1FxdkFnPT0iLCJtYWMiOiJjMjJhYWQ3ZjczMDgwOTExZDI5Njc5OTY4YTg5ZjgxMGI1MDlmYmNkZDJkZTFmNDA5YWMyZjRjOTYxYzc0YzNlIn0%3D;'
},
})
.then((results) => {
const status = results.status
if(typeof result === 'undefind'){
return status
}
const indexDatas = results.data[0]
return indexDatas
}).catch(
error => {}
);
答案 0 :(得分:0)
您可以在浏览器中打开,因为您已在web.php中添加了路由。 为了从api打开,您必须在api.php中添加路由。