我使用 express js 作为后端,并且还在 react js 的 package.json 中添加了后端代理。在它曾经使用 fetch 方法引发错误并转移到 axios 方法以防止这种情况之前。数据为 json 格式,在邮递员上复制粘贴以检查后端后完全正常工作。
import React ,{useState} from 'react'
import './contact.css'
import axios from "axios"
const Contact = (e) => {
const [email, setEmail] = useState('')
const [description,setDescription]=useState('');
const[message,setMessage]=useState('')
const [name ,setName] = useState('')
const url='localhost:5000/api/contact'
const contactClick=async (e)=>{
const subject="contacting"
e.preventDefault();
const formData={
name:name,
email:email,
subject:subject,
description:description
}
console.log(JSON.stringify(formData));
axios.post(url, JSON.stringify(formData))
.then(res => setMessage('email sent'))
.catch(err => {setMessage('Unable to sent email ')
return console.log(err)})
};
return (
<>
<div className='form__container' >
<form onSubmit={contactClick} className='contact__form'>
{message}
<input type="email" placeholder='Email' value={email} required onChange={(e)=>setEmail(e.target.value)
} />
<input type="text" placeholder='name' value={name} required onChange={e=>setName(e.target.value)} />
<input type="textarea" placeholder='Description' className='text-area' value={description} onChange={(e)=>setDescription(e.target.value)}/>
<input type="submit" title="Submit" />
</form>
</div>
</>
)
}
export default Contact