This very same React APP was working till yesterday and suddenly today it stopped working completely. The fetch is not working at all, it not sending the HTTP request at all as observed the Network tab of Firefox. What is wrong with this? It was the same code that perfectly worked yesterday and suddenly today it stops to work.
As you can see that there is absolutely no response from the server. Why there is no response code against the POST request, as seen in the first line?
React Code:
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
export default function Login(props) {
const [email_id, setEmailId] = useState({ email_id: "" });
const [password, setPassword] = useState("");
const history = useHistory();
const submit = () => {
let finalOrder = JSON.stringify(email_id);
fetch("http://localhost:8080/Project/customer/login", {
method: "POST",
headers: { "Content-type": "application/json" },
body: finalOrder,
}).then((res) => {
if (res.ok) {
history.push("/AllProducts");
}
});
};
// sessionStorage.setItem("customer_id", JSON.stringify(result));
// alert(sessionStorage.getItem("customer_id"));
// history.push("/AllProducts");
const handleEmailChange = (e) => {
setEmailId({ email_id: e.target.value });
};
const handlePasswordChange = (e) => {
setPassword(e.target.value);
};
return (
<form>
<h3>Sign In</h3>
<div className="form-group d-flex w-25 p-3 position-relative">
<label>Email address : </label>
<input
type="email"
className="form-control"
placeholder="Enter email"
value={email_id.email_id}
onChange={handleEmailChange}
/>
</div>
<div className="form-group d-flex w-25 p-3">
<label>Password : </label>
<input
type="password"
className="form-control"
placeholder="Enter password"
value={password}
onChange={handlePasswordChange}
/>
</div>
<div className="form-group d-flex w-25 p-3">
<div className="custom-control custom-checkbox">
<input
type="checkbox"
className="custom-control-input"
id="customCheck1"
/>
<label className="custom-control-label" htmlFor="customCheck1">
Remember me
</label>
</div>
</div>
<button
onClick={submit}
className="btn btn-primary btn-block d-flex w-25 p-3"
>
Submit
</button>
</form>
);
}
What is this weird behavior? Can anyone help? #CrossOrigin("http://localhost:3000/") added in the JAVA controller.Thanks in advance.
PS: Getting perfect response in ARC.
Now it is giving the following error:
"Error in the console : Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource." got resolved automatically by adding type="button" to the button. Sounds weird but true.
Related
When I use the postman backend it works fine. But when using React and trying to add data to the database gives a 400 error.
When I use the console.log(newpost) it gives a new post object on the console. But I can't send the data to the database. How to fix this?
postman image
My React Code:
import React, {useState} from "react";
import axios from "axios";
export default function AddPost(){
const [topic,setTopic] = useState("")
const [dec,setDec] = useState("")
const [cate,setCate] = useState("")
function sendData(e){
e.preventDefault();
const newpost = {
topic,
dec,
cate
}
axios.post("http://localhost:8000/post/save",newpost)
.then(()=>{
alert("post added")
setTopic ("")
setDec ("")
setCate("")
}).catch((err)=>{
alert(`Not inserted ${err}`)
})
}
return(
<div className="container">
<form onSubmit={sendData} >
<div className="mb-3">
<label htmlFor="name" className="form-label">topic</label>
<input type="test" className="form-control" id="name" aria-describedby="emailHelp" onChange={(e)=>{
setTopic(e.target.value)
}} />
</div>
<div className="mb-3">
<label htmlFor="Age" className="form-label">description</label>
<input type="test" className="form-control" id="Age" onChange={(e)=>{
setDec(e.target.value)
}}/>
</div>
<div className="mb-3">
<label htmlFor="Gender" className="form-label">postCategory</label>
<input type="test" className="form-control" id="Gender" onChange={(e)=>{
setCate(e.target.value)
}}/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
<div/>
</div>
)
}
As per your postman's request, the request body is not correctly being passed from react code.The expected key name doesn't match. You need to change newpost variable as follows:
const newpost = {
topic,
description: dec,
postCategory: cate
}
Try adding named keys.
For example:
const newpost = {
topic: 'test',
dec: 'test',
cate: 'test'
}
I'm new to Next.js/React, and I am trying to build out a simple contact form and protect it with Cloudflare Turnstile. Without Turnstile, I have it working with no issue. The form submits to the API and sends the email out.
Enviroment:
Next.js 13 using 'use client'
importing:
import { useState } from 'react';
import { Turnstile } from '#marsidev/react-turnstile';
However, now that I am trying to check the form submission with Turnstile, I can never get the input field containing the response token. I can inspect the form and see the input field with the response token filled out. Here is my code:
Form
<form onSubmit={handleSubmit}>
<div className="flex flex-col gap-4">
<div className="form-control w-full max-w-md">
<label className="label" htmlFor="name">
<span className="label-text">Name</span>
</label>
<input
type="text"
id="name"
placeholder="Your Name"
required
className="input w-full max-w-md"
name="name"
onChange={(e) => {
setName(e.target.value);
}}
/>
</div>
<div className="form-control w-full max-w-md">
<label className="label" htmlFor="email">
<span className="label-text">Email</span>
</label>
<input
type="text"
id="email"
placeholder="Your Email"
required
className="input w-full max-w-md"
name="email"
onChange={(e) => {
setEmail(e.target.value);
}}
/>
</div>
<div className="form-control w-full max-w-md">
<label className="label" htmlFor="subject">
<span className="label-text">Subject</span>
</label>
<input
type="text"
id="subject"
placeholder="Subject"
required
className="input w-full max-w-md"
name="subject"
onChange={(e) => {
setSubject(e.target.value);
}}
/>
</div>
<div className="form-control">
<label className="label" htmlFor="message">
<span className="label-text">Message</span>
</label>
<textarea
className="textarea-bordered textarea h-48 w-full max-w-md"
id="message"
placeholder="Your message"
required
name="message"
onChange={(e) => {
setMessage(e.target.value);
}}
></textarea>
</div>
<Turnstile siteKey={cfSiteKey} />
<button type="submit" className="btn-primary btn w-full max-w-md">
Submit
</button>
</div>
</form>
Handler
let cfSiteKey: string;
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [subject, setSubject] = useState('');
const [message, setMessage] = useState('');
const [submitted, setSubmitted] = useState(false);
if (process.env.NEXT_PUBLIC_CLOUDFLARE_TURNSTILE_SITE_KEY) {
cfSiteKey= process.env.NEXT_PUBLIC_CLOUDFLARE_TURNSTILE_SITE_KEY;
} else {
throw new Error('Cloudflare Turnstile Secret Key Not Set');
}
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const formData = new FormData();
const token = formData.get('cf-turnstile-response');
console.log(token);
const data = {
name,
email,
subject,
message,
token,
};
fetch('/api/contact', {
method: 'POST',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then((res) => {
console.log('Response received');
if (res.status === 200) {
console.log('Response succeeded!');
setSubmitted(true);
setName('');
setEmail('');
setSubject('');
setMessage('');
}
});
};
Above, token always returns null when I submit the form. What am I missing or doing wrong here?
I guess I will answer my question.
I had tried many things inside new FormData() but they did not work. So I left it blank and looked elsewhere in my code for the problem.
The answer, along with correct typing is the following inside the handler:
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const token = formData.get('cf-turnstile-response') as string;
console.log(token);
Now the token is available and sent correctly to the API.
So ive got this error, im guessing its something with my use navigate, but im not shure.
Ive have read alot and searched for the solution but i cant find any way to solve the issue.
The issue only comes after ive have logged in. At the moment i dont have any access token on the backend.
react_devtools_backend.js:4026 Warning: Cannot update a component (BrowserRouter) while rendering a different component (Login). To locate the bad setState() call inside Login, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at Login (http://localhost:3000/static/js/bundle.js:3571:82)
at div
at LoginPage
at Routes (http://localhost:3000/static/js/bundle.js:129199:5)
at Router (http://localhost:3000/static/js/bundle.js:129132:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:127941:5)
import React from 'react';
import { useRef, useState, useEffect } from 'react'
// import { useContext } from 'react'
//import AuthContext from './context/AuthProvider';
import axios from './api/axios';
const LOGIN_URL = '/login';
const REG_URL = '/newUser'
export default function Login() {
const [authMode, setAuthMode] = useState("signin");
const changeAuthMode = () => {
setAuthMode(authMode === "signin" ? "signup" : "signin");
}
//const { setAuth } = useContext(AuthContext);
const userRef = useRef();
const errRef = useRef();
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const [errMsg, setErrMsg] = useState('');
const [success, setSuccess] = useState(false);
const [register, setRegister] = useState(false);
useEffect(() => {
userRef.current.focus();
}, [])
useEffect(() => {
setErrMsg('');
}, [userName, password])
const handleRegister = (e) => {
// prevent the form from refreshing the whole page
e.preventDefault();
// set configurations
const RegConfiguration = {
method: "post",
url: REG_URL,
data: {
userName,
password,
},
};
// make the API call
axios(RegConfiguration)
.then((result) => {
setRegister(true);
})
.catch((error) => {
error = new Error();
});
};
///HANDLE Login part.
const handleLogin = async (e) => {
e.preventDefault();
try {
await axios.post(LOGIN_URL,
JSON.stringify({ userName, password }),
{
headers: { 'Content-type': 'application/json' },
withCredentials: false,
}
);
//const token = response?.data?.token;
//setAuth({ userName, password, token })
//console.log(JSON.stringify(respone));
setUserName('');
setPassword('');
setSuccess(true);
} catch (err) {
if (!err?.response) {
setErrMsg('No Server Response');
} else if (err.response?.status === 400) {
setErrMsg('Missing Username or Password');
} else if (err.response?.status === 401) {
setErrMsg('Unauthorized');
}
else {
setErrMsg('Login Failed');
}
errRef.current.focus();
}
}
const Navigate = useNavigate();
if (authMode === "signin") {
return (
<> {success ? (
Navigate('/authlog')
) : (
<div className="Auth-form-container">
<form className="Auth-form" >
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="text-center">
Not registered yet?{" "}
<span className="link-primary" onClick={changeAuthMode} >
Sign Up
</span>
</div>
<div className="form-group mt-3">
<label>Username </label>
<input
className="form-control mt-1"
id='userName'
ref={userRef}
name="userName"
value={userName}
placeholder="username"
onChange={(e) => setUserName(e.target.value)}
/>
</div>
<div className="form-group mt-3">
<label>Password</label>
<input
className="form-control mt-1"
name="password"
type="password"
id='password'
value={password}
placeholder="password"
required
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="d-grid gap-2 mt-3">
<button
type="submit"
className="btn btn-primary"
onClick={(e) => handleLogin(e)}
>
Logga in
</button>
<p ref={errRef} className={errMsg ? "errmsg" : "offscreen"} aria-live="assertive">{errMsg}</p>
</div>
</div>
</form>
</div>
)}</>
)
}
// "Register page"
return (
<div className="Auth-form-container">
<form className="Auth-form" onSubmit={(e) => handleRegister(e)}>
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="text-center">
Already registered?{" "}
<span className="link-primary" onClick={changeAuthMode}>
Go to Sign In
</span>
</div>
<div className="form-group mt-3">
<label>Register Your Username here</label>
<input
className="form-control mt-1"
name="userName"
value={userName}
placeholder="ure username here:"
onChange={(event) => setUserName(event.target.value)}
/>
</div>
<div className="form-group mt-3">
<label>Register Youre password</label>
<input
className="form-control mt-1"
type="password"
name="password"
value={password}
placeholder="ure password here"
onChange={(event) => setPassword(event.target.value)}
/>
</div>
<div className="d-grid gap-2 mt-3">
<button type="submit" className="btn btn-primary" onClick={handleRegister}>
Registera
</button>
{/* display success message */}
{register ? (
<p className="text-success">You Are Now Registered Successfully</p>
) : (
<p className="text-danger">Please register your account here</p>
)}
</div>
</div>
</form>
</div>
);
}
I am new in reactjs and working on nextjs framework,i am trying to integrate "newsletter" section,for this
i created "api" so whenever i pass email in url, email will be save in my db via api, so now i am trying to use this
api in "newsletter" section but i am getting following error
"TypeError: _ctx.t0.response is undefined"
Here is my api url
https://myurl.com?email=loremipsum#gmail.com
Here is my code (inside "components" folder)
import React, { useEffect, useState } from "react";
function Subscribe() {
const [email, setEmail] = useState('')
const [state, setState] = useState('idle')
const [errorMsg, setErrorMsg] = useState(null)
const subscribe = async (e) => {
e.preventDefault()
setState('Loading')
try {
const response = await axios.post('https://myurl.com?email=', { email })
console.log(response)
setState('Success')
setEmail('')
} catch (e) {
console.log(e.response.data.error)
setErrorMsg(e.response.data.error)
setState('Error')
}
}
return (
<div className="container">
<div className="row">
<div className="col-md-7 col-sm-12 col-lg-7 ft-img">
<img src="img/xchanger.png" />
</div>
<div className="col-md-5 col-sm-12 col-lg-5 ft-form">
<form className="row g-3">
<div className="col-12">
<input type="subscribe" className="form-control" id="subscribe2" name="email" type="email" placeholder="Please Subscribe" value={email} onChange={(e) => setEmail(e.target.value)}/>
<button disabled={state === 'Loading'} type="submit" className="btn btn-primary mb-3" onClick={subscribe}> subscribe </button>
</div>
{state === 'Error' && (
<ErrorState className="error-state">{errorMsg}</ErrorState>
)}
{state === 'Success' && (
<SuccessState>Awesome, you've been subscribed!</SuccessState>
)}
</form>
</div>
</div>
</div>
)
}
export default Subscribe
I am brand new to React and things are coming along nicely, but I am getting stuck really badly on this concept. I've been at this point for a couple of days now and I think my brain is just getting overwhelmed by all the new concepts.
I work in a job where I help customers implement some controls that the company sells in their projects. I work with our .NET desktop stuff mostly. My team is doing a side project to create what is basically a StrawPoll clone for the sake of learning React/Node/MongoDB and getting more experience with a full development life cycle since most of what we do is just little code snippets.
I've got some of the basic components set up, but I'm getting really confused when it comes to creating and working with dynamically created components. If someone could show me what to do or explain what to do I would appreciate it so much.
You can find the branch I'm working on here: https://github.com/TylerBarlock/gcCE-Survey/tree/poll-components-cont
The part I'm currently stuck on is in src/Components/Poll/PollCreate.js and PollCreateAnswerOption.js
PollCreate.js:
//Main component for poll creation
import React, { Fragment, useState, useRef } from "react";
import PollCreateAnswerOption from "./PollCreateAnswerOption";
const PollCreate = (props) => {
// const [enteredTitle, setEnteredTitle] = useState("");
// const [enteredDescription, setEnteredDescription] = useState("");
const [enteredAnswer, setEnteredAnswer] = useState("");
const [selectedPrivate, setSelectedPrivate] = useState("");
const [selectedMultiple, setSelectedMultiple] = useState("");
const [selectedLogin, setSelectedLogin] = useState("");
const [selectedIpcheck, setSelectedIpcheck] = useState("");
const enteredTitleRef = useRef();
const enteredDescriptionRef = useRef();
const enteredAnswerRef = useRef();
const titleChangeHandler = (event) => {
//setEnteredTitle(event.target.value);
};
const descriptionChangeHandler = (event) => {
//setEnteredDescription(event.target.value);
};
const answerOptionChangeHandler = (answer) => {
//setEnteredAnswer(answer);
};
const privateSelectedHandler = (event) => {
setSelectedPrivate(event.target.value);
};
const multipleSelectedHandler = (event) => {
setSelectedMultiple(event.target.value);
};
const loginSelectedHandler = (event) => {
setSelectedLogin(event.target.value);
};
const ipcheckSelectedHandler = (event) => {
setSelectedIpcheck(event.target.value);
};
const addAnswerOptionHandler = (event) => {
console.log("add answer clicked");
};
const deleteAnswerOptionHandler = (event) => {
console.log("delete clicked");
};
const onSubmitHandler = (event) => {
//cancel default form submit behavior (reloads page)
event.preventDefault();
const enteredTitle = enteredTitleRef.current.value;
const enteredDescription = enteredDescriptionRef.current.value;
//const enteredAnswer = enteredAnswerRef.current.value;
//object to hold all data about the new poll being created
const newPollData = {
title: enteredTitle,
description: enteredDescription,
answerOptions: [
{
id: enteredAnswer.id,
text: enteredAnswer.text,
},
],
options: {
private: selectedPrivate,
multiple: selectedMultiple,
login: selectedLogin,
ipcheck: selectedIpcheck,
},
};
//send the new poll data up to the Poll component
props.onSaveNewPoll(newPollData);
console.log(newPollData.title);
console.log(newPollData.description);
console.log(newPollData.answerOptions);
};
return (
<React.Fragment>
<form onSubmit={onSubmitHandler}>
<h2 className="mb-4 text-center">Create a Poll</h2>
<div className="text-left">
<div className="grid grid-cols-1 mb-4">
<h4 className="mb-2">Title</h4>
<input
type="text"
placeholder="Ask your question..."
onChange={titleChangeHandler}
ref={enteredTitleRef}
></input>
</div>
</div>
<div className="text-left">
<div className="grid grid-cols-1 mb-4">
<h4 className="mb-2">Description (optional)</h4>
<input
type="text"
placeholder="Describe the poll..."
onChange={descriptionChangeHandler}
ref={enteredDescriptionRef}
></input>
</div>
</div>
<div className="text-left">
<div className="grid grid-cols-1 mb-2 formtext">
<h4 className="mb-2">Answer Options</h4>
<PollCreateAnswerOption
onAnswerOptionChange={answerOptionChangeHandler}
ref={enteredAnswerRef}
onAnswerOptionDelete={deleteAnswerOptionHandler}
/>
<div className="flex">
<input
type="text"
className="mb-3 formtext w-full"
placeholder="Add an answer..."
onChange={answerOptionChangeHandler}
></input>
<button
className="btn-alt-onwhite p-1 h-9"
type="button"
onClick={deleteAnswerOptionHandler}
>
X
</button>
</div>
<div className="flex">
<input
type="text"
className="mb-3 formtext w-full"
placeholder="Add an answer..."
onChange={answerOptionChangeHandler}
></input>
<button
className="btn-alt-onwhite p-1 h-9"
type="button"
onClick={deleteAnswerOptionHandler}
>
X
</button>
</div>
</div>
</div>
<button
className="btn-primary mb-2"
type="button"
onClick={addAnswerOptionHandler}
>
Add Answer
</button>
<div className="text-left">
<div className="grid grid-cols-1 mb-6">
<h4 className="mb-2">Options</h4>
<div className="flex items-center">
<input
type="checkbox"
value=""
className="mx-3"
onChange={privateSelectedHandler}
></input>
<p>Private (only via direct link)</p>
</div>
<div className="flex items-center">
<input
type="checkbox"
value=""
className="mx-3"
onChange={multipleSelectedHandler}
></input>
<p>Allow multiple choices</p>
</div>
<div className="flex items-center">
<input
type="checkbox"
value=""
className="mx-3"
onChange={loginSelectedHandler}
></input>
<p>Voters must log in to vote</p>
</div>
<div className="flex items-center">
<input
type="checkbox"
value=""
className="mx-3"
onChange={ipcheckSelectedHandler}
></input>
<p>Check for duplicate IP</p>
</div>
</div>
</div>
<button type="submit" className="btn-primary mx-2">
Create Poll
</button>
<button type="button" className="btn-alt-onwhite mx-2">
Advanced Settings
</button>
</form>
</React.Fragment>
);
};
export default PollCreate;
PollCreateAnswerOption.js:
import React, { useState, useRef } from "react";
const PollCreateAnswerOption = React.forwardRef((props, ref) => {
const [enteredAnswerOption, setEnteredAnswerOption] = useState();
const answerOptionChangeHandler = (event) => {
setEnteredAnswerOption(event.target.value);
props.onAnswerOptionChange(event.target.value);
};
const deleteAnswerOptionHandler = (event) => {
props.onAnswerOptionDelete(event);
};
return (
<div className="flex">
<input
type="text"
className="mb-3 formtext w-full"
placeholder="Add an answer..."
onChange={answerOptionChangeHandler}
ref={ref}
></input>
<button
className="btn-alt-onwhite p-1 h-9"
type="button"
onClick={deleteAnswerOptionHandler}
>
X
</button>
</div>
);
});
export default PollCreateAnswerOption;
I'm OK with most of the form, but I'm confused on how I should generate 3 PollCreateAnswerOption components, allow the user to add and delete PollCreateAnswerOptions, and then put the data from each of them into my newPollData object.
I apologize in advance if the code is confusing or hard to read. There's a lot of things in here that are half-implemented from me trying all kinds of stuff. I tried to clean it up as much as I could.
There are currently both useState and useRef hooks in place because I don't know which I should use here and I was messing with both.
Thank you in advance to anyone who takes a look at this! I really appreciate the help, and I promise I did a lot of googling and reading before this point, but my brain is just fried at this point...