I’m working on a React frontend and Laravel backend to manage product data. When I try to send a POST request to my Laravel API using the fetch method, I keep getting a 419 status code in the response. I understand that this might be related to CSRF protection in Laravel, but I’m not sure how to resolve it for API calls.
const handleSubmit = (e) => {
e.preventDefault();
const productData = {
barcode: barcode,
product_name: productName,
description: description,
stock: Number(stock),
price: Number(price)
};
fetch('http://127.0.0.1:8000/api/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(productData),
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
};
I suspect it has something to do with the CSRF token, but I thought that Laravel APIs don’t require CSRF tokens. Is there a way to bypass this for API requests, or am I missing something else?
3