0
Problem
I am not consulting my API nodejs with Axios. I have tested the backend numerous times with Postman and everything works correctly, Focusing with Xios always returns the same error. If anyone can help, I’d appreciate it.
Excerpt from the API that is being consulted
server.post('/insert', (req, res, next) => {
const today = new Date();
const userData = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
created: today
}
knex('users')
.where('email', req.body.email)
.then((data) => {
if (data.length) {
res.json("usuario já existente");
} else {
knex('users').insert(userData)
.then((data) => {
res.json("usuario cadastrado com sucesso!");
})
.catch((error) => {
res.json("erro ao cadastrar usuário!")
});
}
})
.catch(error => {
res.send('error ' + error);
});
});
Client side of the application - consultation with Axios
// Pacotes
import React from 'react';
import { Button, Card, Container, Col, Form, Row } from 'react-bootstrap';
import { useForm, ErrorMessage } from 'react-hook-form';
import { NavLink } from 'react-router-dom';
import axios from 'axios';
// Estilo
import './Login.css';
export default (props) => {
const { register, handleSubmit, errors } = useForm();
const onSubmit = (data) => {
axios.post('http://localhost:3003/insert',{
first_name: data.firstName,
last_name: data.lastName,
email: data.email,
password: data.password
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
return (
<Container id="loginContainer" fluid>
<Row className="h-100">
<Col lg="5" className="h-100 mx-auto">
<Card id="loginCard">
<Card.Header className="bg-white border-0">
<h4>Sing-Up</h4>
</Card.Header>
<Card.Body>
<Form onSubmit={handleSubmit(onSubmit)}>
<Form.Control type="text" className="rounded-pill mb-3" placeholder="firstName" name="firstName" autoComplete="off" ref={register({ required: true, maxLength: 20 })} />
<Form.Control type="text" className="rounded-pill mb-3" placeholder="lastName" name="lastName" autoComplete="off" ref={register({ required: true, maxLength: 20 })} />
<Form.Control type="text" className="rounded-pill mb-3" placeholder="email" name="email" autoComplete="off" ref={register({ required: true, maxLength: 20 })} />
<Form.Control type="text" className="rounded-pill mb-3" placeholder="password" name="password" autoComplete="off" ref={register({ required: true, maxLength: 20 })} />
<Button type="submit" variant="primary" className="rounded-pill mb-2" block>Submit</Button>
</Form>
<NavLink type="button" className="btn btn-success btn-block rounded-pill" to="/singIn">Sing-In</NavLink>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
)
}
Error that is returning
CORS problem, that is, you will have to enable in the Api the access to those resources. This has not to do with the front but with the service!
– LeAndrade