【发布时间】:2020-12-25 04:48:06
【问题描述】:
我使用 Laravel 7 作为 REST API 并启用 CORS 并将 ReactJS 作为前端。
我可以向http://127.0.0.1:8000/api/auth/login or register 提出请求,但如果我将在此 url 上从经过身份验证的用户那里获取信息:http://127.0.0.1:8000/api/auth/me,则 cors 将无法在反应中处理我来自 axios 的请求。
如果我没有错过任何东西,我会看看,但我不认为有我使用的代码:
我现在使用 JWT 进行身份验证基本路由和它的基本
AuthController。
AuthController
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
// I have try to except the me route here but that make nothing.
$this->middleware('auth:api', ['except' => ['login','register']]);
}
/**
* Get a JWT via given credentials.
*
* @return JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return JsonResponse
*/
public function me()
{
dd(auth()->user());
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory('api')->getTTL() * 60
]);
}
public function register(Request $request)
{
$data = $request->all();
$data['password'] = bcrypt($data['password']);
return User::create($data);
}
}
CORS Configuration
<?php
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
Profile.js
import React from 'react';
import { loadProgressBar } from 'axios-progress-bar'
import 'axios-progress-bar/dist/nprogress.css'
import jwtDecode from 'jwt-decode'
import axios from 'axios'
export default class Profile extends React.Component {
state = {
user: null,
}
componentDidMount() {
loadProgressBar()
axios.post(axios.defaults.baseURL + 'auth/me')
.then((res) => {
console.log(res)
})
.catch((err) => {console.log(err)})
// if (localStorage.getItem('token')){
// const token = jwtDecode(localStorage.getItem('token'))
// console.log(token)
// }
}
render() {
return (
<div>
<p>Profile Page</p>
</div>
)
}
}
My index.js with interceptor and default baseURL for authentification, ...
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:8000/api/'
if (localStorage.getItem('token')) {
axios.interceptors.request.use(config => {
let prefix = '?'
if (config.url.includes(prefix)) {
prefix = '&'
}
config.url += prefix+'token='+localStorage.getItem('token')
return config
})
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
【问题讨论】:
标签: javascript php reactjs laravel axios