簡體   English   中英

POST請求適用於Postman,但不適用於axios或.fetch()

[英]POST request works with Postman, but not with axios or .fetch()

我有一個問題,我現在已經工作了幾天,但找不到解決方案。 我創建了一個帶有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); 

我的數據庫有三個模型。 事件,類別和用戶: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);
    }

}

而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響應,但在數據庫中只有“created_at”和“updated_at”填充,其余只是一個空字符串。 EventController中的Log-statment顯示,看起來Request-object為空。 但是看一下Firefox-developer工具,我發現數據是在請求體中發送的。

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

謝謝大家已經為你提供的幫助Marco

編輯:由於不明顯,API和前端都在同一主機上運行; localhost:8000所以這不是一個CORS問題。 我首先在localhost:8080上運行前端,但是我通過在同一台服務器上運行它來消除它。

正如預期的那樣,當沒有人真正能夠直接回答我的問題時,我的錯誤並不明顯。 我今天用freind認識到,我實際發送的請求與我在代碼中寫的不同。 通過一些搜索,我發現我的webpack.config在某種程度上錯誤配置並將代碼發布在錯誤的目錄中。 但由於已經有一個“較舊的”js文件,頁面看起來正確但沒有我的API調用的更改。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM