Laravel API + React 前端請求,Axios 回傳 404 - Access-Control-Allow-Origin
<p>我正在嘗試從 React 向 Laravel API 發出 POST 請求。當我在開發模式下發送請求時,請求成功,但當我在Apache2 上部署API(:8000) 和前端(:80) 時,請求被嚴格模式策略阻止,並且CORS 錯誤表明我的請求缺少訪問控制- Allow-Origin 和404 作為回應。但 Laravel 和 React 頁面可以在瀏覽器中存取。為了發出請求,我使用 Axios。
而網站應該有相同的基本 URL <code>http://localhost</code>
我嘗試了很多解決方案,但沒有一個適合我。 </p>
<h1>Laravel 10.x 核心</h1>
<p>我看到許多用戶建議製作中間件,將標頭添加到伺服器回應中。Laravel 中預設加入了類似的內容(<code>conf/cors.php</code>);
我的文件看起來像這樣</p>
<pre class="brush:php;toolbar:false;">'paths' => ['http://127.0.0.1:8000','http://localhost','api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => ['*'],
'max_age' => 0,
'supports_credentials' => false,</pre>
<p>它在 <code>Kernel.php</code> 中註冊如下</p>
<pre class="brush:php;toolbar:false;">protected $middlewareAliases = [
// 'cors' => \App\Http\Middleware\Cors::class, <- this is custom middleware not in use now
'cors' => \Illuminate\Http\Middleware\HandleCors::class,
'auth' => \App\Http\Middleware\Authenticate::class,
……
protected $middleware = [
// \App\Http\Middleware\Cors::class, <- This is custom
middleware not in use now
\Illuminate\Http\Middleware\HandleCors::class,</pre>
<p>這是我使用自訂中間件時 <code>api.php</code> 中的內容</p>
<pre class="brush:php;toolbar:false;">Route::group(['middleware'=>'cors','prefix'=>'api'], function ()
{
Route::post('/signup',[AuthController::class, 'signup']);
Route::post('/login',[AuthController::class, 'login']);
Route::post('/logout',[AuthController::class, 'logout']);
Route::post('/user/post',[PostController::class,'createPost']);
Route::get('/user/post',[PostController::class,'getPostsInMonth']);
Route::post('/media/upload',[UploadController::class,'upload']);
});</pre>
<p>即使使用自訂中間件也沒有成功</p>
<pre class="brush:php;toolbar:false;">class Cors
{
public function handle(Request $request, Closure $next): Response
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Origin, X-Requested-With');
}
}</pre>
<h1>在 Apache Laravel VirtualHost 檔案中加入標頭</h1>
<pre class="brush:php;toolbar:false;"><VirtualHost *:8000>
ServerName website.com
ServerAlias *.website.com
ServerAdmin webmaster@localhost
DocumentRoot .../laravel/public
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization"
<Directory ".../laravel">
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization"
Order allow, deny
Allow from all
Require all granted
</Directory>
</VirtualHost></pre>
<p>React Apache VirtualHost 檔案看起來與 Laravel 檔案非常相似</p>
<p>我沒有成功:(</p>
<h1>Laravel/public 中的 .htaccess</h1>
<pre class="brush:php;toolbar:false;"><IfModule mod_headers.c>
Header set Cross-Origin-Resource-Policy 'cross-origin'
Header set Access-Control-Allow-Origin "*"
</IfModule></pre>
<h1>設定API位址作為代理</h1>
<p>在<code>package.json</code>中我加入了這一行</p>
<pre class="brush:php;toolbar:false;">"proxy": "http://localhost:8000",</pre>
<p>也嘗試使用<code>http-proxy-middleware</code>包
和react/src資料夾中的<code>setupProxy.js</code></p>
<pre class="brush:php;toolbar:false;">const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api/*',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};</pre>
<h1>axios 用戶端腳本</h1>
<pre class="brush:php;toolbar:false;">import axios from "axios";
const axiosClient = axios.create({
baseURL: "http://127.0.0.1:8000/api",
})
axiosClient.interceptors.request.use((config)=>{
const token = localStorage.getItem('ACCESS_TOKEN');
config.headers = {
'Authorization': `Bearer ${token}`,
'Access-Control-Allow-Origin': '*'
}
return config;
})
axiosClient.interceptors.response.use((response)=>{
return response;
},(error)=>{
const {response} = error;
if(response && response.status == 401){
localStorage.removeItem('ACCESS_TOKEN');
}
throw error;
})
export default axiosClient;</pre>
<p>我知道我的許多設定使我的網站不安全,但這僅用於開發目的。
請幫我已經為此掙扎了三天><</p>
<p>這是我得到的結果(抱歉堆疊不希望我因為格式問題上傳圖片)</p>
<pre class="brush:php;toolbar:false;">![1]: https://pasteboard.co/feqZ6JrGrvBM.png
![2]: https://pasteboard.co/nluAk8scYXzY.png
![3]: https://pasteboard.co/JF7yiHhH4XtB.png</pre></p>