I made a form to collect email from users and give alert when data is successfully. When I enter any value in input, it gives me two errors:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/emailcoll. (Reason: CORS request did not succeed). Status code: (null)
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
How do I resolve it?
Below is code of function where the component is:
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch('http://localhost:3001/emailcoll', {
method: 'POST',
mode:"no-cors",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (response.ok) {
alert("Data Saved Successfully!")
}
};
below is code of form:
<form onSubmit={handleSubmit} className={styles.subs}>
<label className={styles.substext}>Stay updated on our all upcoming events!</label>
<input onChange={handleChange} value={formData.email} name="email" className={styles.subsinput} placeholder="[email protected]"/>
<button type="submit" className={styles.subsbut}>Subscribe</button>
</form>
below is server code:
app.post('/emailcoll', async (req, res) => {
const { email } = req.body;
const filePath = './emailcoll.xlsx';
let workbook;
let worksheet;
workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile(filePath);
worksheet = workbook.getWorksheet('Sheet 1');
worksheet.columns = { header: 'Email', key: 'email' }
worksheet.addRow({email});
await workbook.xlsx.writeFile(filePath);
res.send(STATUS_CODES)
})
app.listen(3001)
I tried using extensions for unblocking Access Control Allow Origin. Still same problem.
I have also included mode:”no-cors” in function.