我知道我有很多解决方案可以解决这类问题。但我认为我几乎已经尝试了大部分而没有效果。
我使用PHP Laravel的经验非常好,但不适用于前端库或VueJS或ReactJS等框架。我计划用ReactJS扩展我的前端部分知识。
我创建了一个样品项目,即食品订购系统。这些是表: -
用户迁移表
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
食物迁移表
public function up()
{
Schema::create('foods', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description')->default('');
$table->boolean('in_stock')->default(1);
$table->timestamps();
});
}
Food_user迁移表
public function up()
{
Schema::create('food_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('quantity');
$table->boolean('is_served')->default(0);
$table->timestamps();
});
}
我的路线和相关的控制器: -
web.php
<?php
Route::get('/', function () {
return view('welcome');
});
Route::resource('food', 'FoodController');
Route::get('/allfood', 'FoodController@index');
Route::post('/addfood', 'FoodController@create');
// Route::group(['middleware' => 'cors'], function($router){
// Route::post('/addfood', 'FoodController@create');
// });
FoodController
<?php
namespace App\Http\Controllers;
use App\Food;
use Illuminate\Http\Request;
class FoodController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return response()->json(Food::all());
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$newfood = Food::create([
'name' => request('foodname'),
'description' => request('fooddesc'),
'in_stock' => 1,
]);
return response()->json(Food::all());
}
}
我可以使用axios
Main.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Food from './Food';
export default class Main extends Component {
constructor() {
super();
this.state = {
foods: [],
currentPage: 1,
}
}
componentDidMount() {
axios({
method: 'get',
url: 'http://localhost:8000/allfood'
})
.then(response => {
this.setState({ foods: response.data });
});
}
renderFoods() {
return this.state.foods.map(foods => {
return (
<div className="col-md-8 col-md-offset-2" key={foods.id}>
<div className="panel panel-default">
<div className="panel-heading">{ foods.name }</div>
<div className="panel-body">
{ foods.description }
</div>
</div>
</div>
);
})
}
changePage(pagenum) {
this.setState({currentPage:pagenum});
}
render() {
switch(this.state.currentPage) {
case 1:
return (
<div className="container-fluid" style={{marginTop: 50 + 'px'}}>
<div className="top-right links">
<a href="#" onClick={() =>this.changePage(2)}>Add Food</a>
<a href="#" onClick={() =>this.changePage(1)}>Order Food</a>
</div>
<div className="row text-center">
<h2>List of Menu</h2>
</div>
<div className="row">
{ this.renderFoods() }
</div>
</div>
);
break;
case 2:
return (
<div>
<div className="container-fluid" style={{marginTop: 50 + 'px'}}>
<div className="top-right links">
<a href="#" onClick={() =>this.changePage(2)}>Add Food</a>
<a href="#" onClick={() =>this.changePage(1)}>Order Food</a>
</div>
</div>
<Food/>
</div>
);
break; }
}
}
if (document.getElementById('main')) {
ReactDOM.render(<Main />, document.getElementById('main'));
}
但要添加新记录(新食物)。我被困在这里。
Food.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class Food extends Component {
constructor() {
super();
this.state = {
newFood: {
name: '',
description: '',
instock: 0
},
foods: []
}
}
submitMenu () {
var foody = this.state.newFood;
console.log(foody);
var testpost = axios({
method: 'post',
url: 'http://localhost:8000/addfood',
data: {
name: foody.name,
description: foody.description,
in_stock: foody.instock
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
console.log(testpost);
}
handleInput(key, e) {
var state = Object.assign({}, this.state.newFood);
state[key] = e.target.value;
this.setState({newFood: state });
}
render() {
return (
<div className="container-fluid" style={{marginTop: 50 + 'px'}}>
<div className="row text-center">
<h2>Add Menu</h2>
</div>
<div className="row">
<div className="col-md-8 col-md-offset-2">
<div className="panel panel-default">
<div className="panel-body">
<form onSubmit={this.submitMenu.bind(this)} method="POST">
<div className="form-group">
<label>Food Name</label>
<input type="text" className="form-control" placeholder="Food Name" name="foodname" onChange={(e)=>this.handleInput('name',e)}/>
</div>
<div className="form-group">
<label>Food Description</label>
<textarea className="form-control" name="fooddesc" onChange={(e)=>this.handleInput('description',e)}></textarea>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="instock" value="1"/> In Stock?
</label>
</div>
<button type="submit" className="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
);
}
}
当我在表单中输入新信息并提交时。 Laravel抛出错误: -
Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException
No message
当我查看浏览器的控制台日志时,我在这里看到: -
> Object { name: "Deep Fried Chicken", description: "Dipped with chill sauce", instock: 0 }
> Promise { <state>: "pending" }
那么这里有什么问题?我试过了: -
\App\Http\Middleware\VerifyCsrfToken::class
kernel.php
。axios
我怀疑我使用axios
post方法是不对的。不过,我只是按照文档。
这是我在完整的javascript前端开发方面的第一次体验。而且我对javascript的了解非常少。我希望我的问题在这里得到适当的解释......
答案 0 :(得分:0)
你的代码是对的,你只需要通知create
方法,Request
作为参数,以获取从axios
代码发送的所有数据。
ur create
就像这样,你需要将http成功状态代码返回到客户端代码(201):
有关http代码的更多信息,请阅读本文:link
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$newfood = Food::create([
'name' => $request->get('foodname'),
'description' => $request->get('fooddesc'),
'in_stock' => 1,
]);
//return response()->json(Food::all()); /* u don't need to return data here */
return response()->json([],201);
}