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

Mai*_*007 6 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);
Run Code Online (Sandbox Code Playgroud)

我的数据库有三个模型。事件,类别和用户:Category.id <--- 1:n ---> Event.category_id || Event.updated_by <--- n:1 ---> 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

和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');
     }
}
Run Code Online (Sandbox Code Playgroud)

就像我说的那样,当我使用Postman发送POST请求时,一切都按预期工作了。但是通过我的fetch()函数,我得到了200个响应,但是在数据库中仅填充了“ created_at”和“ updated_at”,其余的只是一个空字符串。显示EventController中的Log语句,这似乎是Request对象为空。但是在Firefox-developer工具中,我看到数据是在请求正文中发送的。

有什么想法吗?如果需要,我还可以发送其他代码文件。

谢谢大家已经为您提供帮助Marco

编辑:不太明显,API和Frontend都在同一主机上运行;本地主机:8000,所以它不是CORS问题。我首先在localhost:8080上运行Frontend,但通过在同一服务器上同时运行它们来消除了这种情况。

Mai*_*007 2

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

TL;DR 请注意,所有内容都位于您需要的地方,然后上面的代码就是正确的:-)