POST请求适用于Postman,但不适用于axios或.fetch()

时间:2018-01-13 14:46:07

标签: javascript php fetch postman lumen

我遇到了一个问题,我现在已经工作了几天,而且无法找到解决方案。我创建了一个带有Lumen的API和一个带有ReactJS的前端。这一切都适用于GET请求,但是当我发送POST请求时它会失败。出于某些奇怪的原因,当我使用Postman发送请求时,请求会起作用。 现在一些代码!

首先发送请求的JS脚本:



import moment from 'moment';
import React, {Component} from 'react';
import { Modal, Form, Button, Input, DatePicker, Select, message } from 'antd';

const {RangePicker} = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;

const api_url = 'api/v1/';

class NewEventForm extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            confirmLoading: false,
            categories: []
        };

        this.onCreate = this.onCreate.bind(this);
        this.onCancel = this.onCancel.bind(this);
    }

    componentDidMount() {
        fetch(api_url + 'category')
        .then(results => {
            return results.json();
        }).then(data => {
            let categories = data.map((cat) => {
                return (
                    <Option key={cat.id} value={cat.id}>{cat.name}</Option>
                    );
            });
            this.setState({categories: categories});
        });
    }
    
    updateStates() {
        this.props.updateState();
        this.setState({confirmLoading: false});
    }

    onCreate() {
        this.props.form.validateFields((err, values) => {
            this.setState({
                confirmLoading: true
            });

            if (err) {
                this.setState({
                    confirmLoading: false
                });
                return;
            }
            
            let event = {
                title: values.title,
                description: values.description,
                start_time: values.date[0],
                end_time: values.date[1],
                category_id: values.category
            };
            
            fetch(api_url + 'event', {
                method: 'POST',
                /* headers are important*/
                headers: {
                    "content-type":"application/json",
                    "cache-control":"no-cache",
                    "accept":"*/*",
                },
                body: JSON.stringify(event)
            }).then(response => {
                if(response.ok) {
                    return response.json();
                }
                throw new Error("Antwort der API war nicht 'Ok'!");
            }).then(data =>{
                this.updateStates();
                
                message.success('Das Ereignis wurde erfolgreich eingetragen!');              
            }).catch(error => {
                //console.log(error);
                this.updateStates();
                
                message.error('Das Ereignis wurde nicht erstellt. Bitte versuche es später nochmal!'); 
            });
        });
    }
    onCancel(e) {
        e.preventDefault();

        this.updateStates();
    }

    render() {
        const {getFieldDecorator, getFieldError} = this.props.form;

        return(
                <Modal title="Neue Veranstaltung hinzufügen" okText="Eintragen" confirmLoading={this.state.confirmLoading} visible={this.props.visible} onOk={this.onCreate} onCancel={this.onCancel}>
                    <Form layout="vertical">
                        <FormItem label="Titel">
                            {getFieldDecorator('title', {
                                rules: [{required: true, message: 'Bitte einen Titel angeben!' }],
                            })(
                            <Input />
                            )}
                        </FormItem>
                        <FormItem label="Beschreibung">
                            {getFieldDecorator('description')(<Input type="textarea" />)}
                        </FormItem>
                        <FormItem label="Kategorie">
                            {getFieldDecorator('category', {
                                rules: [{required: true, message: 'Bitte einen Kategorie auswählen!' }],
                            })(
                            <Select placeholder="Kategorie auswählen...">
                                {this.state.categories}
                            </Select>
                            )}
                        </FormItem>
                        <FormItem label="Zeitraum" className="collection-create-formlast-form-item">
                            {getFieldDecorator('date', {
                                rules: [{required: true, message: 'Bitte einen Zeitraum auswählen!' }],
                            })(
                            <RangePicker
                                showTime={{
                                    hideDisabledOptions: true,
                                    defaultValue: [moment('00:00', 'HH:mm'), moment('00:00', 'HH:mm')],
                                    format: 'HH:mm'
                                }}
                                format="DD.MM.YYYY HH:mm"
                                />
                            )}
                        </FormItem>
                    </Form>
                </Modal>
                );
    }
}

export const NewEventModal = Form.create()(NewEventForm);
&#13;
&#13;
&#13;

我的数据库有三个型号。活动,类别和用户: Category.id&LT; --- 1:N ---&GT; Event.category_id || Event.updated_by&LT; --- N:1 ---&GT; User.id

现在是EventController:

<?php

namespace App\Http\Controllers;

use App\Event;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;


class EventController extends Controller{


    public function index(){
        $Events = Event::all();

        return response()->json($Events);  
    }

    public function getEvent($id){  
        $Event = Event::with(['category', 'user'])->find($id);

        return response()->json($Event);
    }

    public function createEvent(Request $request){
        $User  = \App\User::find(1);
        $Category = \App\Category::find(1);

        $Event = new Event;
        $Event->fill($request->all());
        $Event->user()->associate($User);
        $Event->category()->associate($Category);

        $obj = '';
        foreach ($request->all() as $key => $value) {
            $obj .= '[' . $key . '] => "' . $value . '"; ';
        }

        \Log::warning('Test: ' . $obj);

        $Event->save();

        return response()->json($request);  
    }

    public function deleteEvent($id){
        $Event = Event::find($id);
        $Event->delete();

        return response()->json('deleted');
    }

    public function updateEvent(Request $request,$id){
        $Event = Event::find($id);
        $Event->title = $request->input('title');
        $Event->description = $request->input('description');
        $Event->start_time = $request->input('start_time');
        $Event->end_time = $request->input('end_time');
        $Event->save();

        return response()->json($Event);
    }

}

EventModel:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
     protected $fillable = ['title', 'description', 'start_time', 'end_time'];

     public function user() {
         return $this->belongsTo('App\User', 'updated_by');
     }

     public function category() {
         return $this->belongsTo('App\Category');
     }
}

就像我说的那样,当我使用Postman时,一切按预期工作,发送POST请求。但是使用我的fetch() - 函数,我得到一个200响应,但在数据库中只有&#34; created_at&#34;和&#34; updated_at&#34;填充,其余只是一个空字符串。 EventController中的Log-statment显示,看起来Request-object为空。但是看一下Firefox-developer工具,我发现数据是在请求体中发送的。

那么任何想法?如果需要,我也可以发送其他代码文件。

谢谢大家的帮助 马可

编辑:由于不明显,API和前端都在同一台主机上运行; localhost:8000因此它不是CORS问题。我首先在localhost上运行了前端:8080,但我通过在同一台服务器上运行它来消除它。

1 个答案:

答案 0 :(得分:3)

正如预期的那样,当没有人真正能够直接回答我的问题时,我的错误并不明显。我今天用freind认识到,我实际发送的请求与我在代码中写的不同。 通过一些搜索,我发现我的webpack.config在某种程度上错误配置并将代码发布在错误的目录中。但由于已经有一个“较旧”的js文件,页面看起来是正确的,但没有我的API调用的更改。

TL; DR注意一切都在你需要的地方,然后上面的代码是正确的: - )