I have this fetch where I'm trying to post a form in MongoDB.
When I fill the form I get this back:
SyntaxError: Unexpected end of input at ContactRequest.js:3:1
And I don't know why, because the fetch receives the data from the form and testing the endpoint in postman it works perfectly.
The fetch should works because I used the same Fetch in other projects.
This is the fetch component.
const contactRequest = (params) => {
console.log(`Test ${JSON.stringify(params)}`);
fetch(`http://localhost:4000/contact`, {
method: "POST",
body: JSON.stringify(params),
mode: "no-cors",
headers: {
'Content-Type': 'application/json'
}})
.then(res => res.json())
.catch((e) => console.error(e));
};
export default contactRequest;
This is the form component:
import React, {useState} from 'react';
import contactRequest from '../Request/ContactRequest';
import './Contact.css';
const initialState = {
nameAndSurname: "",
email: "",
phoneNumber: "",
message: "",
};
const Contact = () => {
const [contactData, setContactData] = useState(initialState);
const handlerInput = (e) => {
setContactData({
...contactData,
[e.target.name] : e.target.value
});
};
const handlerSubmit = (e) => {
e.preventDefault();
setContactData(initialState);
contactRequest(contactData);
alert("Hemos recibido tu mensaje.");
}
return (
<div>
<form onSubmit={handlerSubmit}>
<label className="nameAndSurname-label">
Nombre y Apellido: <br/>
<input
id="nameAndSurname"
type="text"
name="nameAndSurname"
placeholder="Ingrese su nombre y apellido"
onChange={handlerInput}
value={contactData.nameAndSurname}
required/> <br/>
</label>
<div className="email-phoneNumber-div">
<label>
Email: <br/>
<input
id="email"
type="email"
name="email"
placeholder="Ingrese su email"
onChange={handlerInput}
value={contactData.email}
required/> <br/>
</label>
<label>
Numero de teléfono: <br/>
<input
id="phoneNumber"
type="number"
name="phoneNumber"
placeholder="Ingrese su numero de teléfono"
onChange={handlerInput}
value={contactData.phoneNumber}
required/> <br/>
</label>
</div>
<label>
Mensaje: <br/>
<input
id="message"
type="text"
name="message"
placeholder="Ingrese su mensaje"
onChange={handlerInput}
value={contactData.message}
required/> <br/>
</label>
<label>
Al enviar este formulario, acepto los terminos y condiciones.
</label>
<button
id="submit-btn"
type="submit"
value="Submit">Enviar</button>
</form>
</div>
</div>
)
}
export default Contact;
This is the Endpoint.
const express = require('express');
const router = express.Router();
const Contact = require('../models/Contact.js');
router.post('/contact', (req, res) => {
console.log(req.body);
console.log(req.text);
let contact = new Contact()
contact.nameAndSurname = req.body.nameAndSurname
contact.email = req.body.email
contact.phoneNumber = req.body.phoneNumber
contact.message = req.body.message
contact.save((err, contactStored) => {
if(err) {
res.status(500).send({message: `Error ${err}`})
}else {
res.status(200).send({contact: contactStored})
}
})
})
module.exports = router;
Why are you using mode: "no-cors"? This results in an "opaque" response, without body, so without anything to convert to json
Related
After I send data in json I want to save the data, all the data is received fine, but it does not recognize the user, even though it is indeed connected according to the tests I did. i am getting this error: ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x106fd12d0>>": "Vendors.user" must be a "User" instance.
but the user is log in.
view.py:
#csrf_exempt
def store_register(request):
if request.method == 'POST':
form = json.loads(request.body)
print(request.user,form)
vendor = Vendors.objects.create(user=request.user,store_name=form['storeName'],company_name=form['companyName'],img=form['storeImage'],business_email=form['businessEmail'],pay_pal=form['payPalEmail'])
vendor.save()
return JsonResponse({'test':'test'})
react:
class RegisterBody extends React.Component {
constructor (props) {
super (props);
this.state = {
url: ''
}
}
SendInput = () => {
const storeName = document.getElementById('storeName').value
const companyName = document.getElementById('companyName').value
const storeImage = document.getElementById('storeImage').value
const businessEmail = document.getElementById('businessEmail').value
const payPalEmail = document.getElementById('payPalEmail').value
this.setState({storeName:storeName,companyName:companyName,storeImage:storeImage,businessEmail:businessEmail,payPalEmail:payPalEmail})
fetch('/store-register', {
method: 'POST',
body: JSON.stringify({
'storeName':storeName,
'companyName':companyName,
'storeImage':storeImage,
'businessEmail':businessEmail,
'payPalEmail':payPalEmail
}),
headers: {
'Content-type': 'application/json; charset=UTF-8'
},
})
}
render () {
return (
<div>
<label>Store Name</label>
<input type={"text"} name={"storeName"} id={"storeName"}></input>
<br></br>
<label>Company Name</label>
<input type={"text"} name={"companyName"} id={"companyName"}></input>
<br></br>
<label>Store Image</label>
<input type={"file"} name={"storeImage"} id={"storeImage"}></input>
<br></br>
<label>Business Email</label>
<input type={"email"} name={"businessEmail"} id={"businessEmail"}></input>
<br></br>
<label>Paypal Email</label>
<input type={"email"} name={"payPalEmail"} id={"payPalEmail"}></input>
<br></br>
<button onClick={() => this.SendInput()}>Register</button>
</div>
)
}
}
export default RegisterBody
I have a form for creating a post with an image. I get this error message: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string. Yet in several post found on the internet I saw that he was doing the same way as me. If anyone can help me that would be cool. thanks in advance.
const FormCreatePastry = () =>{
const [ nameProduct, setNameProduct ] = useState("");
const [ ingredient, setIngredient ] = useState("");
const [ imageUrl, setImageUrl ] = useState();
const [ price, setPrice ] = useState("");
const [ nameShopPastry, setNameShopPastry ] = useState("--Choisir une boutique--");
const [ controlForm, setControlForm ] = useState(false)
const handleChange = (e) =>{
const nameShop = e.target.value;
setNameShopPastry(nameShop);
}
const sendForm = (e) =>{
e.preventDefault();
createPastryService(nameProduct, ingredient, imageUrl, nameShopPastry, price)
}
const uploadImage = (e) =>{
const file = e.target.files;
setImageUrl(file)
}
const cancelForm = (e) =>{
e.preventDefault();
}
const cancelImage = (e) =>{
e.preventDefault();
setImageUrl(null)
}
const ErrorForm = () =>{
if (controlForm === true) {
return(
<>
<p>Veuillez remplir tous les champs!</p>
</>
)
}else{
return null
}
}
useEffect(()=>{
console.log(imageUrl)
console.log(nameShopPastry)
if (nameProduct.length < 1 || ingredient.length < 1 || nameShopPastry === "--Choisir une boutique--" || price === "" || imageUrl === "" ) {
setControlForm(true)
}else{
setControlForm(false)
}
},[controlForm,nameShopPastry, ingredient, imageUrl, nameProduct, price])
return(
<form action="">
<label htmlFor="Nom du produit:">
Nom du produit:
<input type="text" value={nameProduct} onChange={(e)=>setNameProduct(e.target.value)} />
</label>
<label htmlFor="Ingrédients">
Ingrédients:
<input type="text" value={ingredient} onChange={(e)=>setIngredient(e.target.value)}/>
</label>
<label htmlFor="">
Prix:
<input type="text" value={price} onChange={(e)=>setPrice(e.target.value)} />
</label>
<label htmlFor="Image du produit">
Image du produit:
<input type="file" value={imageUrl} onChange={uploadImage}/>
<button onClick={cancelImage}>X</button>
</label>
<div>
<p>Sélectionner une boutique</p>
<select onChange={(e)=> handleChange(e)}>
<option value="--Choisir une boutique--">--Choisir une boutique--</option>
<option value="20">Pastry Paris </option>
<option value="23">Pastry Bordeaux</option>
</select>
</div>
<div>
<button disabled={controlForm} onClick={sendForm}>valider</button>
<button onClick={cancelForm}>annuler</button>
</div>
<ErrorForm />
</form>
)
}
export default FormCreatePastry;
In React, an <input type="file"/> is always an uncontrolled component because its value can only be set by a user, and not programmatically. you can refer
react doc.
so do not use value props on input that has a type file.
<input type="file" onChange={uploadImage}/>
I'm building a form using React & Nodejs & MongoDB, where you can fill the form and upload a file with some other text inputs.
However, after i submit, i receive only text inputs in my database. The chosen file (desired to upload) doesn't appear at all in the database. I am expecting to get all the data form (the uploaded file and text inputed) in my database.
I tested my backend and it works correctly (it uploads all the inputs).
Ps: In browser, when i select a file (.pdf) to upload, the file input always shows no file chosen !
Console.dev : Error
{title: 'Miss', fname: 'zaezae', lname: 'zaeazee', email: 'zaea#mail.com', phoneNumber: '12345678', …}
coverLetter: "zaez e az ezae e zae aeae "
cv: ""
email: "zaea#mail.com"
fname: "zaezae"
lname: "zaeazee"
myFile: "C:\\fakepath\\test.pdf"
phoneNumber: "12345678"
title: "Miss"
Formulaire.jsx:29
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then')
at submit (Formulaire.jsx:29:1)
Backend:
server.js:
const express = require('express')
const mongoose = require('mongoose')
const bodyparser = require('body-parser')
const FormRoute = require('./routes/FormRoute')
//database
mongoose.connect('mongodb://localhost:27017/form', { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (err) => {
console.log(err)
})
db.once('open', () => {
console.log("Database connection established!")
})
//app
const app = express()
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
//cors
const cors = require('cors')
app.use(cors())
//server run
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
app.use('/api/form', FormRoute);
Axios.js:
import axios from 'axios'
export const Axios = axios.create({
baseURL: 'http://localhost:5000',
})
Apiroutes.js:
const form = "/api/form"
export const requests = {
formApi: {
store: form + '/store'
}
}
formservices.js:
import { Axios } from "../config/axios";
import { requests } from "../config/apiroutes";
export const FormService = {
store: (data) => {
Axios.post(requests.formApi.store, data)
.then(res => {
return res
})
.catch(err => {
return err
})
}
}
formController.js :
const form = require('../models/FormModel')
const store = (req, res, next) => {
let candidate = new form({
title: req.body.title,
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
phoneNumber: req.body.phoneNumber,
coverLetter: req.body.coverLetter
})
if (req.file) {
candidate.cv = req.file.path
}
candidate.save()
.then(response => {
res.json({
success: true,
message: 'Candidate added successfully!',
data: candidate,
})
})
.catch(error => {
res.json({
success: false,
message: 'An error occured!',
error: error,
})
})
}
module.exports = {
store
}
Frontend:
Formulaire.jsx :
import React, { useState } from 'react'
import Divider from '#mui/material/Divider';
import './Formulaire.css'
import { titles } from '../../mock/titles'
import { FormService } from '../../services/formServices';
const Form = () => {
const [storedata, setstoredata] = useState({
title: '',
fname: '',
lname: '',
email: '',
phoneNumber: '',
cv: '',
coverLetter: ''
})
const handleChange = e => {
const { name, value } = e.target;
setstoredata(prevState => ({
...prevState,
[name]: value
}));
};
const submit = async () => {
console.log(storedata);
await FormService.store(storedata)
.then(res => {
console.log(res);
})
.catch(err => {
return err
})
}
return (
<div className='container'>
<div className='header'>
<div className='title'>
<a className='quizbutton' href="/quiz">Take a Test (Quiz)</a>
<h1>Apply for a Position :</h1>
</div>
</div>
<Divider style={{ maxWidth: '1000px', marginLeft: '250px' }} />
<div id="content">
<div id="formWrapper">
<form id="msform" method='post' action='/uploadFile' enctype="multipart/form-data">
<fieldset id="fieldset3">
<h2 class="fs-title">Please complete the form below for a position with us.</h2>
<h3 class="fs-subtitle">Reference 0001</h3>
{/* <div class="fs-error"></div> */}
<div class="wrapper">
<label for="title">Title :</label>
<select name="title" value={storedata.title} onChange={handleChange}>
<option hidden></option>
{
titles.map((c, i) => {
return (
<option key={i} value={c}>{c}</option>
)
})
}
</select>
<label for="fname">First Name<span>*</span> :</label>
<input type="text" name="fname" value={storedata.fname} onChange={handleChange} id="fname" placeholder="Please enter your first name" required />
<label for="lname">Last Name<span>*</span> :</label>
<input type="text" name="lname" value={storedata.lname} onChange={handleChange} id="lname" placeholder="Please enter your last name" required />
<label for="email">Email<span>*</span> :</label>
<input type="email" name="email" value={storedata.email} onChange={handleChange} id="email" placeholder="Please enter your email" required />
<label for="phoneNumber">Phone N° :</label>
<input type="number" name="phoneNumber" value={storedata.phoneNumber} onChange={handleChange} id="phoneNumber" placeholder="Phone number" />
<label for="CV">Upload CV <span>*</span>:</label>
<input type="file" name="myFile" id="cv" value={storedata.cv} onChange={handleChange} accept="application/msword, application/pdf" placeholder="Cover Letter" required />
<label for="coverLetter">Cover Letter :</label>
<textarea type="text" name="coverLetter" value={storedata.coverLetter} onChange={handleChange} id="coverLetter" placeholder="cover Letter" />
</div>
<br />
<input type="submit" name="submit" class="submit action-button" value="Submit" onClick={submit} />
</fieldset>
</form>
</div>
</div>
</div>
)
}
export default Form
I fixed my problem by changing name="myFile" id="cv" to name="cv" id="cv"
So I'm setting up a login and register page with the firebase authentication and realtime database. However, the authentication works but my data doesn't get pushed into my database. My alert messages are also not popping up and i can't figure it out.
HTML
<form action="../index.html">
<div class="input">
<input type="text" placeholder="Naam" id="name" required>
</div>
<div class="input">
<input type="email" placeholder="E-mail" name="email" id="email" required>
</div>
<div class="right-inner-addon">
<i class="fa-solid fa-eye-slash" id="togglePassword"></i>
<div class="input">
<input type="password" placeholder="Password" name="psw" id="psw" required>
</div>
</div>
<button type="submit" id="submitData" class="registerbtn">Meld je aan</button>
</form>
Javascript
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.3/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.8.3/firebase-auth.js";
import { getDatabase,set,ref } from "https://www.gstatic.com/firebasejs/9.8.3/firebase-database.js";
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const database = getDatabase(app);
submitData.addEventListener('click',(e) =>{
let email = document.getElementById('email').value;
let password = document.getElementById('psw').value;
let name = document.getElementById('name').value
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
set(ref(database, 'users/' + user.uid), {
name: name,
email: email,
password : password
})
.then(() => {
// Data saved successfully!
alert ('Gebruiker succesvol geregistreerd');
})
.catch((error) => {
// The write failed...
alert(error);
});
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
})
I'm hiding my configuration ofcourse.
I currently have a simple next.js website where users can look at projects for an organization, and at the bottom of the page, the user can input a new project through the use of a form with multiple inputs. The database that i am currently using is Supabase.
My code currently takes in user input from each input box and stores them inside the newProject const, after which the data is then parsed into the createNewProject function and sent to Supabase.
const initialState = { solution_id: '', organization_id: '', budget_usd: '',other_info: '',country: '',project_duration_days: '',status: '',date_time_timezone: '' }
export default function Projects({ Projects }) {
useEffect(() => {
console.log(Projects)
}, [])
const [newProject, setProject] = useState(initialState)
console.log("User inputed data")
console.log(newProject)
const {solution_id, organization_id, budget_usd, other_info, country,project_duration_days,status,date_time_timezone} = newProject
const router = useRouter()
function onChange(e) {
setProject(() => ({ ...newProject, [e.target.name]: e.target.value }))
}
async function createNewProject() {
if (!solution_id || !organization_id || !country) return
const id = uuid()
newProject.id = id
const {data} = await supabase
.from('Projects')
.insert([
{ solution_id, organization_id, budget_usd,other_info,country,project_duration_days,status,date_time_timezone }
])
router.push(`/projects/${data.id}`)
}
return (
<div>
{Projects.map(project => {
return (
<div key={project.id}>
<h1><b>{project.Solutions.name} in {project.country}</b></h1>
<h2>Budget USD: {project.budget_usd}</h2>
<h2>Duration: {project.project_duration_days} days</h2>
<h2>Status: {project.status}</h2>
<h2>Organization: {project.Organizations.name}</h2>
<h2>Project Id: {project.id}</h2>
<button type="button" onClick={() => router.push(`/projects/${project.id}`)}>Donate now</button>
<br></br>
</div>
)
})}
<label htmlFor="solution_id ">solution_id</label>
<input onChange={onChange} value={newProject.solution_id} type="text" id="solution_id" name="solution_id" required />
<label htmlFor="organization_id ">organization_id</label>
<input onChange={onChange} value={newProject.organization_id} type="text" id="organization_id" name="organization_id" required />
<label htmlFor="budget_usd ">Last budget_usd</label>
<input onChange={onChange} value={newProject.budget_usd} type="text" id="budget_usd" name="budget_usd" required />
<label htmlFor="other_info ">other_info</label>
<input onChange={onChange} value={newProject.other_info} type="text" id="other_info" name="other_info" required />
<label htmlFor="country ">country</label>
<input onChange={onChange} value={newProject.country} type="text" id="country" name="country" required />
<label htmlFor="project_duration_days ">Project Duration Days</label>
<input onChange={onChange} value={newProject.project_duration_days} type="text" id="project_duration_days" name="project_duration_days" required />
<label htmlFor="status ">status</label>
<input onChange={onChange} value={newProject.status} type="text" id="status" name="status" required />
<label htmlFor="date_time_timezone ">date_time_timezone</label>
<input onChange={onChange} value={newProject.date_time_timezone} type="text" id="date_time_timezone" name="date_time_timezone" required />
<button type="button" onClick={createNewProject} >Submit new project</button>
</div>
)
}
export async function getServerSideProps() {
const fetchOrgs = async () => {
let { data: Organizations, error } = await supabase
.from('Organizations')
.select('*')
return Organizations
}
const fetchSolutions = async () => {
let { data: Solutions, error } = await supabase
.from('Solutions')
.select('*')
return Solutions
}
const fetchProjects = async () => {
let { data: Projects, error } = await supabase
.from('Projects')
.select(`
id,
solution_id,
organization_id,
budget_usd,
country,
project_duration_days,
status,
Solutions(name),
Organizations(name)
`)
.order('id', { ascending: true })
console.log(Projects)
return Projects
}
const Organizations = await fetchOrgs();
const Solutions = await fetchSolutions();
const Projects = await fetchProjects();
return { props: { Solutions, Organizations, Projects } }
}
However, whenever I press the submit button, the console.log for the newProject, would show that there is not data being passed into the variables, only the empty placeholder data in the initialState const. As such, I am unsure about how to pass data from next.js input forms into a variable to be posted into supabase.