简体   繁体   中英

ReactJS - Pass post data to the server

Introduction

A am a beginner with ReactJS and I've tried send one single form data to the php Laravel Controller with method POST, I am using fetch (whatwg-fetch) for server-side rendering and rendering from server to client with method GET works fine.

Error

I am was getting error from console: POST http://localhost:8000/boss 405 (Method Not Allowed) , after the clicking "Submit Button" and the page reloading - Fetch loading is not successful.

Code

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)
{
    //
}
}

your route is a GET request but you are making a POST request, you need change POST to GET in here:

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

This is old post and I try to respond on my own question, when I've become better developer (for year and 3 months elapsed). Maybe this source code should helps someone.

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);
}

There is a little change, I gonna send boss data in response.

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}
     });
    });
  };

And there, in BossInfo.jsx , I add this.setState() for response from backend, in fetch with post method.

Hope this source code someone help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM