I have a problem with my api running on http://localhost:8000, I can send data from the react app running on http://localhost:3000. However, I can't receive the data and the request takes around 10 seconds to be received by the server (api). I use axios to send requests. I also receive this request, I guess its a preflight request but I'm not sure : OPTIONS /api/register 204 0.265 ms - 0
This is my code for the request :
submitHandler(e:FormEvent<HTMLFormElement>) {
e.preventDefault();
let data = {
name: this.state.name,
email: this.state.email,
password: this.state.password,
passwordValidation: this.state.passwordValidation,
}
console.time("post")
axios.post("http://localhost:8000/api/register", data).then((res)=>{
console.log(res.data.errors);
if(res.data.errors !== null){
console.log('Error');
this.setState({errors : res.data.errors})
return;
}
if(res.data.ok){
this.setState({message : "Succesfully registrated !" })
this.setState({toProfile : true})
return;
}
console.log(res);
})
console.timeEnd("post") //around 10ms
}
}));
This is my Controller :
export function createUser(req:Request, res:Response, next:NextFunction) {
console.time("createUser")
const user:any = new UsersSchemaModel(req.body);
user.password = user.hashPassword(user.password); //around 200ms
var errors = validationResult(req);
console.log(req.headers)
if(req.body == '{}') return res.json({error: "You must provide data"})
if (!errors.isEmpty()) {
console.timeEnd('createUser')
return res.send({ errors: errors.mapped() });
}else{
user.save((err:mongoose.Error)=>{
if(err){
console.timeEnd('createUser')
console.log("Error saving user", user);
return next();
}
console.timeEnd('createUser') // around 500ms
res.json({ok:true})
})
}
}
This is my cors options :
app.use(cors({
origin: ['http://localhost:3000'],
methods: ['GET', 'POST', 'DELETE', 'PUT'],
credentials: true, // enable set cookie
}));
Morgan Logs : POST /api/register 200 10021.856 ms - 359
Thanks in advance for any help provided !