REACT调用(Post)到Api (Laravel)返回错误500



我对web开发相当陌生,我目前正在使用laravel和react进行练习。

目前我有一个api调用(post)返回错误500的问题。

下面是php代码:

模型
protected $fillable = [
'id',
'name',
'address',
'phone',
'email'

控制器

public function store(Request $request)
{
$customer = Customer::create($request->all());
return response()->json($customer, 201);
}

Api的路线

Route::apiResource('customers', 'AppHttpControllersCustomerController');
下面是js代码:

服务(customers.js)

export async function addCustomer(customer) 
{
fetch( '/api/customers/', 
{
method:'post',
headers: 
{
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(customer)
})
.then(response => 
{
console.log(response);
return response.json();
})
}

组件(CustomerForm.js)

const CustomerForm = ({customer, showForm}) => {
[...]
const handleSubmit = (e) => 
{
e.preventDefault(); 
addCustomer(model)
.then(i => {}, 
error => 
{
console.log(error.message)
})
.catch(e => 
{
console.log(e)
console.log(response)
}); 
}
/**
* render
*/
return (
[...]
);
}
export default CustomerForm;

错误如下:

POST http://127.0.0.1:8000/api/customers/ 500 (Internal Server Error)
_callee3$   @   app.js:6606
tryCatch    @   app.js:6524
(anonymous) @   app.js:6524
(anonymous) @   app.js:6524
asyncGeneratorStep  @   app.js:6526
_next   @   app.js:6528
(anonymous) @   app.js:6528
(anonymous) @   app.js:6528
_addCustomer    @   app.js:6625
addCustomer @   app.js:6594
handleSubmit    @   app.js:5704
onSubmit    @   app.js:5725
[...]

我做了什么:

  • 同样的调用与postman工作得很好。
  • 在我的html头中有一个csv -token。

任何建议吗?

在浏览器中检查控制台。您可能希望从后端启用CORS

如果有人需要答案,我找到了。

  1. 确保正确配置您的认证系统!在我的例子中,我使用Laravel Sanctum系统时忘记了一些东西。这里是文档:https://laravel.com/docs/9.x/sanctum#spa-authentication

  2. 在POST请求中添加CSRF令牌!这里有一些信息:如何获得Laravel csrf令牌在React中通过fetch post请求发送它?

祝你白天、晚上或任何你喜欢的事愉快!