[英]React + Laravel 7 API - CORS issue
我正在尝试做一个简单的注册表单(只是在学习),但我遇到了 CORS 的问题。 我已经尝试了所有我发现但没有奏效的东西。 据我所知,Laravel 7 已经可以防止 CORS 问题,但我的没有。 这是我的代码:
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group([
'prefix' => 'auth',
], function () {
Route::post('login', 'AuthController@login');
Route::post('signup', 'AuthController@signup');
Route::group([
'middleware' => 'auth:api'
], function () {
Route::get('logout', 'AuthController@logout');
Route::get('user', 'AuthController@user');
});
});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
cors.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Fruitcake\Cors\HandleCors::class,
],
'api' => [
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Fruitcake\Cors\HandleCors::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
应用程序.js
import React from 'react';
import axios from 'axios';
class App extends React.Component {
constructor() {
super();
this.state = {
name: "",
email: "",
password: "",
password_confimation: ""
};
}
/**
* Generic handleChange
* @param {The element changing} e
*/
handleChange = (e) => {
this.setState({
[e.target.name] : e.target.value
});
}
handleSubmit = () => {
const user = {
name: this.state.name,
email: this.state.email,
password: this.state.password,
password_confimation: this.state.password_confimation
};
axios.post("localhost:8000/api/auth/signup", user)
.then(response => {
console.log(response);
console.log(response.data);
});
}
render() {
return (
<div>
<label>Name:
<input type="text" name="name" onChange={this.handleChange.bind(this)} />
</label>
<br />
<label>E-mail:
<input type="text" name="email" onChange={this.handleChange.bind(this)} />
</label>
<br />
<label>Password:
<input type="password" name="password" onChange={this.handleChange.bind(this)} />
</label>
<br />
<label>Password Confirmation:
<input type="password" name="password_confimation" onChange={this.handleChange.bind(this)} />
</label>
<br />
<button onClick={this.handleSubmit}>Sign Up</button>
</div>
);
}
}
export default App;
使用 Postman Laravel 有效,只有在我使用 React 时才会发生。 我究竟做错了什么?
我通过在我的 axios 请求中添加“http://”来解决它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.