ReactJS - 将发布数据传递给服务器

时间:2017-09-28 11:43:16

标签: javascript php laravel reactjs ecmascript-6

简介

我是ReactJS的初学者,我尝试使用方法POST将单个表单数据发送到php Laravel Controller,我使用fetch(whatwg-fetch)进行服务器端渲染并从服务器渲染到客户端用方法GET工作正常。

错误

在点击"提交按钮"后,我从控制台POST http://localhost:8000/boss 405 (Method Not Allowed)收到错误。和页面重新加载 - 获取加载不成功。

代码

root.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import Example from './components/Example';
import Navigation from './components/Navigation';
import Trigger from './components/Trigger';
import BossInfo from './components/BossInfo';

const DOM = document.getElementById('example');


if (document.getElementById('example')) {
ReactDOM.render(
        <div>

                <Navigation/>,
            <div className="container">
                <BossInfo/>
                <Trigger/>,
                <Example />
            </div>
        </div>,
DOM);
}

BossInfo.jsx

import React from 'react';
import 'whatwg-fetch';


export default class BossTable extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        boss: {}
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}



componentDidMount() {
    this.fetchData('http://localhost:8000/boss');
}


fetchData = (url) => {

    fetch(url)
        .then(response => {
            console.log(response);
            if (response.ok) {
                return response.json();
            }
        })
        .then((data) => {
            console.log(data);
            this.setState(() => {
                return {boss: data}
            });
        })
        .catch(function (error) {
            console.log(error);
        });
};


handleChange = (event) => {
    let value = event.target.value;



    this.setState({
        boss:
            {
                id: 1,
                nazev: value,
                hp: "",
                mhp: "",
                mp: "",
                mmp: "",
                zasah: "",
                vyhnuti: "",
                zbroj: "",
                poskozeni: "",
                schopnost1: "",
                schopnost2: "",
                schopnost3: "",
                schopnost4: "",
                schopnost5: "",
            }

    });

};


handleSubmit = (event) => {
    event.preventDefault();

    const {boss}  = this.state;

    let url = 'http://localhost:8000/boss';


    let fetchData = {
        method: 'POST',
        body: boss,
        headers: new Headers()
    };


    fetch(url, fetchData)
    .then( response => {
        console.log("************Response*****************");
        this.fetchData(url);

        if(response.status.code === 404){
            console.log("Chyba: Objekt nenalezen.");
        }

    })


};

render() {
    const {boss}  = this.state;
    if (!boss) {
        return <div>Loading...</div>
    }

    console.log(boss);
    return (
        <div>
           <form id="formular" onSubmit={this.handleSubmit}>
                <label>
                    Name:
                    <input type="text" required value={boss.nazev} onChange={this.handleChange} />
                    </label>
                    <input type="submit"  placeholder='Send message'/>
            </form>
        </div>
    );
}
}

web.php

<?php

Route::get('/', function () {
return view('index');
});

Route::get('boss', 'HomeController@index');

Route::post('data', 'HomeController@update');

HomeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Boss;


class HomeController extends Controller
{

public function index()
{
    $boss = Boss::find(1);
    return response()->json($boss);

}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    //
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{

    //$bossOld = Boss::find(1);


}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    //
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    //
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request)
{
    $id = $request->post('id');
    $boss = Boss::find($id);
    $boss->nazev = $request->post('nazev');
    $boss->save();

    return response()->json('Successfully Updated');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}
}

2 个答案:

答案 0 :(得分:1)

您的路线是GET请求,但您要发出POST个请求,您需要在此处更改POSTGET

let fetchData = {
    method: 'POST', // change to GET
    body: boss,
    headers: new Headers()
};

答案 1 :(得分:0)

这是旧文章,当我成为更好的开发人员(一年零三个月)后,我会尝试回答自己的问题。也许此源代码应该可以帮助某人。

HomeController.php

public function update(Request $request)
{
    $id = $request->post('id');
    $boss = Boss::find($id);
    $boss->nazev = $request->post('nazev');
    $boss->save();

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

有一点变化,我将发送老板数据作为响应。

BossInfo.jsx

 handleSubmit = (event) => {
   event.preventDefault();

   const {boss}  = this.state;

   let url = 'http://localhost:8000/boss';


   let fetchData = {
      method: 'POST',
      body: boss,
      headers: new Headers()
   };


   fetch(url, fetchData)
   .then( response => {
      console.log("************Response*****************");

      if(response.status.code === 404){
        console.log("Chyba: Objekt nenalezen.");
      }
      if (response.ok) {
        return response.json();
      }
   })
   .then((data) => {
     this.setState(() => {
       return {boss: data}
     });
    });
  };

然后,在 BossInfo.jsx 中,我添加了this.setState()来从后端进行响应,以post方法获取。

希望此源代码能对您有所帮助。