[在ReactJs和Laravel中使用Axios时请求失败

问题描述 投票:1回答:2

[我使用ReactJs作为前端引擎,我使用Axios处理请求以通过Laravel从Post表中获取数据,当我获得响应时,我在api.php中设置了路由,console.log它显示了对XMLHttpRequest的访问我的Chrome DevTool出现错误

api.php文件:

<?php

use Illuminate\Http\Request;

Route::get('/', [
    'uses' => 'PagesController@getIndex'
]);

我的控制器文件:

<?php

namespace App\Http\Controllers;

use App\Posts;
use Illuminate\Http\Request;

class PagesController extends Controller
{
    public function getIndex(){
        $post = Posts::all();

        return $post;
    }
}

我的ReactJs文件(App.js):

import React from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';

class App extends React.Component{

    getData(){
        console.log(123);
        axios.get('http://localhost:8000/')
            .then(function (response) {
                console.log(response.data);
            }).catch(function (error) {
            // handle error
            console.log(error);
        });
    }

    render(){
        return (
            <div className="App">
                <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <p>
                        Edit <code>src/App.js</code> and save to amir.
                    </p>
                    { this.getData() }
                    <a
                        className="App-link"
                        href="https://reactjs.org"
                        target="_blank"
                        rel="noopener noreferrer"
                    >
                        Learn React
                    </a>
                </header>
            </div>
        );
    }
}

export default App;

错误屏幕截图:

enter image description here

reactjs laravel laravel-5 axios laravel-5.8
2个回答
0
投票

我解决了我的问题,首先我使用php artisan make:middleware Cors创建了一个中间件,然后Cors类应该像这样:

    <?php

    namespace App\Http\Middleware;

    use Closure;

    class Cors
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            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');
        }
    }

0
投票

您可以通过composer导入laravel-cors软件包

在您的控制台中:composer require barryvdh/laravel-cors

然后在您的app / Http / Kernel.php中将其添加到中间件或仅添加到api(我相信适用于laravel-cors 1.0版及更高版本)

\Fruitcake\Cors\HandleCors::class,

或(在我的其他项目中为0.11.3)

\Barryvdh\Cors\HandleCors::class,
热门问题
推荐问题
最新问题