我使用 Laravel 作为后端,NextJs 作为前端。问题出在发送表格的时候
正确获取csrf token,与cookie中的存储相符。
网页文件.php中的路径是
Route::post('/administracion/nuevo-producto', [ProductosController::class, 'store'])->name('productos');
ProductoController 包括
return response()->json(['message' => 'Datos guardados exitosamente']);
Cors.php:
'paths' => ['api/*', 'getCsrf'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['Content-Type', 'Authorization', 'x-xsrf-token'], // Agregamos 'X-Xsrf-Token' aquí
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
在 kernel.php 中包含
\App\Http\Middleware\VerifyCsrfToken::class
我在 NextJS 中的组件
import Head from 'next/head'
import { useAuth } from '@/hooks/auth'
import { router } from 'next/router'
import { useEffect, useState } from 'react'
import AppLayout from '@/components/Layouts/AppLayout'
import axios from 'axios'
export default function adminIndex() {
const { user } = useAuth()
const rolesAutorizados = [1]
useEffect(() => {
if (user) {
if (!rolesAutorizados.includes(user.id_rol)) {
router.push('/dashboard')
}
}
}, [user])
function getCookie(name) {
if (typeof document !== 'undefined') {
const cookies = document.cookie.split(';')
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim()
if (cookie.startsWith(name + '=')) {
return cookie.substring(name.length + 1)
}
}
}
return null
}
const [nombre, setNombre] = useState('');
const handleSubmit = async e => {
e.preventDefault()
try {
// Crea un objeto con los datos del formulario
const formData = {
nombre,
}
// Agrega el token CSRF al encabezado de la solicitud
const headers = {
'X-XSRF-TOKEN': getCookie('XSRF-TOKEN'),
}
// Realiza la solicitud POST a tu servidor Laravel
const response = await axios.post('/administracion/nuevo-producto', formData, {
headers,
})
// Maneja la respuesta del servidor si es necesario
console.log('Respuesta del servidor:', response.data)
} catch (error) {
console.error('Error al enviar la solicitud:', error)
}
}
return (
<>
<AppLayout
header={
<h2 className="font-semibold text-xl text-gray-800 leading-tight">
Nuevo producto
</h2>
}>
<Head>
<title> Nuevo producto - Mar Nails</title>
</Head>
<div className="py-12">
<div className="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div className="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div className="p-6 bg-white border-b border-gray-200">
<form onSubmit={handleSubmit}>
{/* Campos del formulario */}
<div>
<label>Nombre:</label>
<input type="text" value={nombre} onChange={(e) => setNombre(e.target.value)} />
</div>
{/* ...otros campos del formulario */}
<button type="submit">Enviar</button>
</form>
</div>
</div>
</div>
</div>
</AppLayout>
</>
)
}
您的 Axios 标头不包含与 Laravel 进行 JSON 通信所需的标头。将其添加到您的 Axios 标头配置中:
'Accept': 'application/json'
'Content-Type': 'application/json'
这样 Laravel 就会知道它需要以 Json 格式响应你。它可能无法解决根本问题,但至少您会得到 JSON 响应。
您可以在这里阅读更多内容: https://laraveldaily.com/post/laravel-api-error-html-json-how-to-fix