aaagggg1233
aaagggg1233

Reputation: 13

Not getting any response from Axios to front end

Hi I am not getting any response with axios.get. I am very new to react etc. I want the code to give an error when the wrong password is entered or whenever one of the fields is blank. I am using mongoDB and below is my code.

For my backend login.js file

const router = require('express').Router();
let User = require('../models/users.model');

router.get("/login", async (req, res) => {

try {

    const { email, pass } = req.body;

    if (!email || !pass)
        return res.status(401).json({ msg: "Not all fields have been entered." });
    const user = await users.findOne({ email: email });
    if (!user)
        return res.status(401).json({ msg: "Not account with this email." });
    const isMatch = await users.findOne({ pass: pass });
    if (!isMatch) return res.status(401).json({ msg: "Invalid credentials." });

} catch (err) {
    res.status(500).json({ error: error.message });
}
});

On the front end I have this

 constructor(props) {
        super(props);
        this.state = {
            email: '',
            password: '',
            errors: {}
        };


    this.handlePassChange = this.handlePassChange.bind(this);
    this.handleEmailChange = this.handleEmailChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

}


    handleSubmit(e) {
        e.preventDefault();

        this.setState({
            email: '',
            password: '',
            errors: {}
        }) 

        const user = {
            email: this.state.email,
            password: this.state.password     
        }

        axios.get('http://localhost:3001/api/routes/login.js', user)
            .then(function (response) {
                console.log(response.data);
            })
        window.location.assign('/Dashboard' );

    }

    handleEmailChange(e) {
        this.setState({
            email: e.target.value,
        });
    };

    handlePassChange(e) {
        this.setState({
            password: e.target.value,
        });
    }

Upvotes: 1

Views: 548

Answers (1)

Or Assayag
Or Assayag

Reputation: 6336

Back:

Change

router.get("/login", async (req, res) => {

to

router.post("/login", async (req, res) => {

Front:

Change

axios.get('http://localhost:3001/api/routes/login.js', user)
    .then(function (response) {
        console.log(response.data);
    })

to

axios.post('http://localhost:3001/api/routes/login.js', user)
    .then(function (response) {
        console.log(response.data);
    })

Upvotes: 1

Related Questions