我试图在laravel react.js组合中建立axios示例。我通过以下命令配置了我的项目 作曲者create-project --prefer-dist laravel / laravel react-laravel-basic-8。 PHP的工匠预设反应 npm安装 npm审核修复--force npm安装axios npm run dev PHP工匠服务。 我的web.php文件是
Route::get('/', function () {
return view('welcome');
});
Route::get('add-a-student',function()
{
return view('add_student');
});
Route::get('/testing/','Admin@testing');
我的控制器Admin.php是
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Admin extends Controller
{
public function testing()
{
echo "hello alert";
}
}
我的视图add_student.blade.php是
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<title>React axios</title>
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
<div id="basic"></div>
<script src="{{ asset('js/app.js') }}">
</script>
</body>
</html>
我的jsx文件驻留在resources / assets / js / components / Example.jsx即
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
export default class Example extends Component {
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-8 col-md-offset-2">
<div className="panel panel-default">
<div className="panel-heading">Example Component</div>
<div className="panel-body">
I'm an example component!
</div>
</div>
</div>
</div>
</div>
);
}
}
class Developer extends React.Component{
handlesubmit(e)
{
e.preventDefault();
axios.post('/testing/', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
alert('success');
})
.catch(function (error) {
alert(error);
});
}
render()
{
return(<div><form onSubmit={this.handlesubmit}>
<table>
<tr>
<td>
<label>Date of birth</label>
</td>
<td>
<input type="date" name="dob" />
</td>
</tr>
<tr><td><button type="submit">Add student</button></td>
<td><button type="reset">Cancel</button></td>
</tr>
</table>
</form></div>);
}
}
if (document.getElementById('example')) {
ReactDOM.render(<Example />, document.getElementById('example'));
}
if(document.getElementById('basic'))
{
ReactDOM.render(<Developer />,document.getElementById('basic'));
}
我遇到以下错误错误:尝试通过axios方法提交表单时请求失败,状态码为405。请帮助我修复该错误
答案 0 :(得分:1)
出现此错误的原因是,您正在向 GET 路由发送 POST 请求。
因此,您可以将路由从 GET 更改为 POST ,以允许处理 POST 请求。
更改此
Route::get('/testing/','Admin@testing');
进入
Route::post('/testing/','Admin@testing');