Axios:Vuejs的网络错误

时间:2018-05-12 16:48:03

标签: php node.js laravel webpack vue.js

我正在从localhost进行axios调用:8080(前端)到localhost:8000(后端)。

前端是用vue,webpack和node编写的,而后端是lumen-laravel框架。

这是电话:

mounted() {
        axios.get('localhost:8000/getParentela').then((r) => {
            console.log(r.data);
            this.albero = r.data;
        }).catch((e) => {
            console.log(e);
        });
    },

调用返回的错误是: error

我认为这可能是因为CORS所以我把一个中间件放在我的后端。

就是这样:

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
class CORSMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // TODO: Should check whether route has been registered
        if ($this->isPreflightRequest($request)) {
            $response = $this->createEmptyResponse();
        } else {
            $response = $next($request);
        }
        return $this->addCorsHeaders($request, $response);
    }
    /**
     * Determine if request is a preflight request.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    protected function isPreflightRequest($request)
    {
        return $request->isMethod('OPTIONS');
    }
    /**
     * Create empty response for preflight request.
     *
     * @return \Illuminate\Http\Response
     */
    protected function createEmptyResponse()
    {
        return new Response(null, 204);
    }
    /**
     * Add CORS headers.
     *
     * @param \Illuminate\Http\Request  $request
     * @param \Illuminate\Http\Response $response
     */
    protected function addCorsHeaders($request, $response)
    {
        foreach ([
            'Access-Control-Allow-Origin' => '* ',
            'Access-Control-Max-Age' => (60 * 60 * 24),
            'Access-Control-Allow-Headers' => $request->header('Access-Control-Request-Headers'),
            'Access-Control-Allow-Methods' => $request->header('Access-Control-Request-Methods')
                ?: 'GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS',
            'Access-Control-Allow-Credentials' => 'true',
        ] as $header => $value) {
            $response->header($header, $value);
        }
        return $response;
    }
}

我仍然认为它是CORS,因为如果直接使用localhost:8000调用API,它就可以工作..

我读到可能是ublock阻止了请求,所以我禁用了它但没有任何变化。

但错误仍然存​​在,我知道该怎么做。 感谢。

0 个答案:

没有答案