Laravel API + React 前端请求,Axios 返回 404 - Access-Control-Allow-Origin
P粉492959599
P粉492959599 2023-09-02 12:50:08
0
1
401
<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' =&gt; ['http://127.0.0.1:8000','http://localhost','api/*', 'sanctum/csrf-cookie'], 'allowed_methods' =&gt; ['*'], 'allowed_origins' =&gt; ['*'], 'allowed_origins_patterns' =&gt; [], 'allowed_headers' =&gt; ['*'], 'exposed_headers' =&gt; ['*'], 'max_age' =&gt; 0, 'supports_credentials' =&gt; false,</pre> <p>它在 <code>Kernel.php</code> 中注册如下</p> <pre class="brush:php;toolbar:false;">protected $middlewareAliases = [ // 'cors' =&gt; \App\Http\Middleware\Cors::class, &lt;- this is custom middleware not in use now 'cors' =&gt; \Illuminate\Http\Middleware\HandleCors::class, 'auth' =&gt; \App\Http\Middleware\Authenticate::class, ... protected $middleware = [ // \App\Http\Middleware\Cors::class, &lt;- 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'=&gt;'cors','prefix'=&gt;'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) -&gt;header('Access-Control-Allow-Origin', '*') -&gt;header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS') -&gt;header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Origin, X-Requested-With'); } }</pre> <h1>在 Apache Laravel VirtualHost 文件中添加标头</h1> <pre class="brush:php;toolbar:false;">&lt;VirtualHost *:8000&gt; ServerName website.com ServerAlias *.website.com ServerAdmin webmaster@localhost DocumentRoot .../laravel/public Header add Access-Control-Allow-Origin &quot;*&quot; Header add Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot; &lt;Directory &quot;.../laravel&quot;&gt; Header set Access-Control-Allow-Origin &quot;*&quot; Header set Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot; Order allow, deny Allow from all Require all granted &lt;/Directory&gt; &lt;/VirtualHost&gt;</pre> <p>React Apache VirtualHost 文件看起来与 Laravel 文件非常相似</p> <p>我没有成功:(</p> <h1>Laravel/public 中的 .htaccess</h1> <pre class="brush:php;toolbar:false;">&lt;IfModule mod_headers.c&gt; Header set Cross-Origin-Resource-Policy 'cross-origin' Header set Access-Control-Allow-Origin &quot;*&quot; &lt;/IfModule&gt;</pre> <h1>设置API地址作为代理</h1> <p>在<code>package.json</code>中我添加了这一行</p> <pre class="brush:php;toolbar:false;">&quot;proxy&quot;: &quot;http://localhost:8000&quot;,</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 &quot;axios&quot;; const axiosClient = axios.create({ baseURL: &quot;http://127.0.0.1:8000/api&quot;, }) axiosClient.interceptors.request.use((config)=&gt;{ const token = localStorage.getItem('ACCESS_TOKEN'); config.headers = { 'Authorization': `Bearer ${token}`, 'Access-Control-Allow-Origin': '*' } return config; }) axiosClient.interceptors.response.use((response)=&gt;{ return response; },(error)=&gt;{ const {response} = error; if(response &amp;&amp; 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>
P粉492959599
P粉492959599

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!