hope you can clarify this issue:
I am trying to create a simple react form updating the data in the database, my React code is as it follows:
import React, { useState, useEffect } from 'react';
export default function Form() {
const [email, setEmail] = useState('');
const [name, setName] = useState('');
const [text, setText] = useState('');
const handleEmail=(e)=>{
setEmail(e.target.value)
}
const handleName=(e)=>{
setName(e.target.value)
}
const handleText=(e)=>{
setText(e.target.value)
}
const handleSubmit=(e)=>{
e.preventDefault();
if(name&&email&&text!==''){
sendData()
}else{
console.log('fill the stuf')
}
}
const sendData=()=>{
fetch('http://www.contact.test/api/contact',{
method:'post',
body:JSON.stringify(
{email,name,text}
),
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
}
}).then(function(response){
response.json().then(function(resp){
console.log(resp)
})
})
setText('')
setEmail('')
setName('')
}
return (
<>
<form onSubmit={handleSubmit}>
<label>Email</label>
<input onChange={handleEmail} type="email" value={email} placeholder="Enter email"/>
<label>Name</label>
<input onChange={handleName} type="text" value={name} placeholder="Enter Name"/>
<label>Text</label>
<textarea onChange={handleText} value={text} placeholder="Enter Text"/>
<button type="submit">Send</button>
</form>
</>
)
}
however I am getting an error when fetching the data,
Form.jsx:43 Uncaught (in promise) SyntaxError: Unexpected end of JSON input
at Form.jsx:43
the most important part for the fetch is this one, line 43 comented for you to identify:
const sendData=()=>{
fetch('http://www.contact.test/api/contact',{
method:'post',
body:JSON.stringify(
{email,name,text}
),
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
}
}).then(function(response){
response.json().then(function(resp){>**//this is line 43**
console.log(resp)
})
})
setText('')
setEmail('')
setName('')
}
my bakcend is with Laravel 7:
class ContactController extends Controller
{
function contact(Request $request)
{
$contact = new Contact;
$contact->name=$request->input('name');
$contact->email=$request->input('email');
$contact->text=$request->input('text');
$contact->save();
return $contact;
}
}
the route is
Route::post('/contact', 'ContactController@contact');
I am a bit confused since I managed to send some request into the DB but suddently it started to complain about CORS, I installed the chrome extension and now this happens.
Hope you have a suggestion.
Thanks
edit the problem apppeared when trying to set up an automatic email after submiting the form, in the developer tools/network/headers when I fill the .env file in laravel with the information of the email, 2 new headers appear: