gpt4 book ai didi

Laravel ReactJS Post 方法不允许

转载 作者:行者123 更新时间:2023-12-03 14:31:51 26 4
gpt4 key购买 nike

我知道对于我遇到的此类问题有很多解决方案。但我想我几乎已经尝试了其中的大部分,但没有一个有效。

我对 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();
});
}

我的路线和相关 Controller :-

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

食品 Controller

<?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" }

那么这里有什么问题呢?我尝试过:-

  1. 安装并配置 Laravel Cors 以绕过 CSRF。
  2. 创建特定的 Laravel Cors 中间件组。
  3. 将方法从 POST 更改为 GET。
  4. 从以下位置删除(注释)\App\Http\Middleware\VerifyCsrfToken::classkernel.php.
  5. 尝试在 axios 上对数据进行硬编码。

我怀疑我使用的 axios post 方法不正确。不过,我只是按照文档进行操作。

这是我第一次完整的 javascript 前端开发经验。而我对javascript的了解非常非常少。我希望我的问题是正确且得到充分解释的......

最佳答案

你的代码是正确的,你只需要通知你的create方法,该方法以Request作为参数来获取从你的axios发送的所有数据代码。

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

关于Laravel ReactJS Post 方法不允许,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48636829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com