在React app中没有'Access-Control-Allow-Origin'。但刷新后消失了

时间:2018-05-30 23:04:17

标签: laravel reactjs api ecmascript-6 cors

我在React中创建了一个简单的Web应用程序作为前端,而Laravel作为后端。我成功地从数据库中获取数据但是当我在数据库中发布内容时,我在控制台中收到错误消息:

  

对预检请求的响应未通过访问控制检查:否   请求中存在“Access-Control-Allow-Origin”标头   资源。因此不允许原点'null'访问。如果是不透明的   响应满足您的需求,将请求的模式设置为'no-cors'   在禁用CORS的情况下获取资源。

奇怪的是,当我提交表单并刷新页面时,我的数据会显示出来。

我的React任务概述:

default = dict(lower_bound=20, upper_bound=50)
values = getattr(myconfig, name1, default=default)
self.do_x(values['lower_bound'], values['upper_bound'])

我的React服务

import React from 'react';
import * as TaskService from '../_services/Tasks.Service';
import { TaskForm } from '../forms/TaskForm.Component';

export class TaskOverview extends React.Component {
    constructor (props) {
        super(props);
        this.state = {
            tasks: [],
        };
    }

    componentWillMount = () => {       
        TaskService.getAll().then(response => this.setState({ tasks: response }));
    }

    renderTasks = () => {
        let tasks   = this.state.tasks.map((task, i) => {
            return <li key={ i }>{ task.title }</li>
        });

        return tasks;
    }

    onFormSubmit = (data) => {
        TaskService.add(data);
    }

    render = () => {
        return (
            <div>
                <ul>
                    { this.renderTasks() }
                </ul>
                <TaskForm onSubmit={ this.onFormSubmit } />
            </div>
        )
    }
}

我的路线

export const getAll = () => {
    return fetch('http://projects/_own/ToDoLoo/api/public/task-overview').then((response) => {
        if ( response.status === 200 ) {
            return response.json();
        }
        throw new Error('Network response was not ok.');
    })
}

export const add = (task) => {
    return fetch('http://projects/_own/ToDoLoo/api/public/task-add', { 
        method: 'POST',
        body: JSON.stringify(task),
        mode: 'cors', 
        headers: new Headers({
            'Content-Type': 'application/json',
        })
    }).then((response) => {
        if(response.statusText === 'OK') {
            return response.json();
        }
        throw new Error('Network response was not ok.');
    })
}

我的控制器

Route::get('/task-overview',    'TaskController@getTasks');
Route::post('/task-add',        'TaskController@addTask');

我还在

中添加了一个单独的Cors.php Middelware文件
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Task;

class TaskController extends Controller
{
    public function getTasks () 
    {
        $tasks  = Task::all();
        return $tasks;
    }

    public function addTask (Request $request) 
    {
        $request->validate([
            'title'     => 'required|string',
            'body'      => 'required', 'string'
        ]);

        $task           = new Task;
        $task->title    = $request->title;
        $task->body     = $request->body;
        $task->user_id  = $request->user_id;
        $task->save();

        return back();
    }
}

并将类添加到我的kernel.php

public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, DELETE');
        $response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
        $response->header('Access-Control-Allow-Origin', '*');
        return $response;
    }

我无法弄清楚当我发布任务时我的控制台中出现此错误的方式,刷新页面后错误将消失并添加任务。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

试试这个

$response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers','Origin,X-Requested-With,Content-Type,Accept, Authorization'));