【问题标题】:Not getting any response from Axios to front end没有收到 Axios 对前端的任何响应
【发布时间】:2020-11-28 07:41:03
【问题描述】:

您好,我没有收到关于 axios.get 的任何回复。我对做出反应等很陌生。我希望代码在输入错误密码或其中一个字段为空白时给出错误。我正在使用 mongoDB,下面是我的代码。

对于我的后端 login.js 文件

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 });
}
});

在前端我有这个

 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,
        });
    }

【问题讨论】:

  • api/routes/login.js 更改为/login。您正在将 uri 传递给 axios 而不是文件路径

标签: node.js reactjs axios


【解决方案1】:

返回:

改变

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

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

正面:

改变

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2021-12-25
    • 2015-10-12
    相关资源
    最近更新 更多