POST 请求失败,无法登录

Posted

技术标签:

【中文标题】POST 请求失败,无法登录【英文标题】:POST Request Failed, unable to login 【发布时间】:2021-08-30 09:35:30 【问题描述】:

我在尝试通过前端登录时收到 Request Failed 错误:

但是,当我通过 thunder 客户端 输入电子邮件 ID 和密码时,我可以:

我正在输入正确的 ID 和密码,这是我的要求:

但我得到的回报是:

这是我的源代码:

前端

userAction.js

import axios from "axios";
import 
  USER_LOGIN_FAIL,
  USER_LOGIN_REQUEST,
  USER_LOGIN_SUCCESS,
 from "../constants/userConstants";

export const login = (email, password) => async (dispatch) => 
  try 
    dispatch(
      type: USER_LOGIN_REQUEST,
    );

    const config = 
      headers: 
        "Content-Type": "appllication/json",
      ,
    ;

    const  data  = await axios.post(
      "/api/users/login",
       email, password ,
      config
    );

    dispatch(
      type: USER_LOGIN_SUCCESS,
      payload: data,
    );

    localStorage.setItem("userInfo", JSON.stringify(data));
   catch (error) 
    dispatch(
      type: USER_LOGIN_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    );
  
;

userReducer.js

import 
  USER_LOGIN_FAIL,
  USER_LOGIN_REQUEST,
  USER_LOGIN_SUCCESS,
  USER_LOGOUT,
 from "../constants/userConstants";

export const userLoginReducer = (state = , action) => 
  switch (action.type) 
    case USER_LOGIN_REQUEST:
      return  loading: true ;
    case USER_LOGIN_SUCCESS:
      return  loading: false, userInfo: action.payload ;
    case USER_LOGIN_FAIL:
      return  loading: false, error: action.payload ;
    case USER_LOGOUT:
      return ;
    default:
      return state;
  
;

store.js

import  createStore, combineReducers, applyMiddleware  from "redux";
import thunk from "redux-thunk";
import  composeWithDevTools  from "redux-devtools-extension";

// reducers
import  userLoginReducer  from "./reducers/userReducers";

const reducer = combineReducers(
  userLogin: userLoginReducer,
);

const userInfoFromStorage = localStorage.getItem("userInfo")
  ? JSON.parse(localStorage.getItem("userInfo"))
  : null;

const initialState = 
  userLogin:  userInfo: userInfoFromStorage ,
;
const middleware = [thunk];

const store = createStore(
  reducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

export default store;

后端

userController.js

const User = require("../models/userModel");
const generateToken = require("../utils/generateToken");

//  @description: Auth user & Get token
//  @route:       POST /api/users/login
//  @access:      Public
exports.authUser = async (req, res, next) => 
  try 
    const  email, password  = req.body;
    const user = await User.findOne( email );

    if (user && (await user.matchPassword(password))) 
      res.json(
        _id: user._id,
        name: user.name,
        email: user.email,
        isAdmin: user.isAdmin,
        token: generateToken(user._id),
      );
     else 
      const error = new Error("Invalid email or password");
      error.status = 401;
      next(error);
    
   catch (error) 
    console.log("_id: ", user._id);
    error = new Error("Invalid user data");
    error.status = 401;
    next(error);
  
;

//  @description: Get user profile
//  @route:       GET /api/users/profile
//  @access:      Private
exports.getUserProfile = async (req, res, next) => 
  try 
    const user = await User.findById(req.user._id);

    if (user) 
      res.json(
        _id: user._id,
        name: user.name,
        email: user.email,
        isAdmin: user.isAdmin,
      );
    
   catch (error) 
    error = new Error("User not found");
    error.status = 404;
    next(error);
  
;

userModel.js

const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const userSchema = mongoose.Schema(
  
    name: 
      type: String,
      required: true,
    ,
    email: 
      type: String,
      required: true,
      unique: true,
      match: [
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]1,3\.[0-9]1,3\.[0-9]1,3\.[0-9]1,3\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]2,))$/,
        "Please enter a valid email address",
      ],
    ,
    password: 
      type: String,
      required: true,
      match: [
        /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]8,$/,
        "Password must contain minimum eight characters, atleast one letter, one number & one speccial character ",
      ],
    ,
    isAdmin: 
      type: String,
      required: true,
      default: false,
    ,
  ,
  
    timestamps: true,
  
);

userSchema.methods.matchPassword = async function (enteredPassword) 
  return await bcrypt.compare(enteredPassword, this.password);
;

// We are encrypting data before saving it
userSchema.pre("save", async function (next) 
  if (!this.isModified("password")) 
    next();
  

  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
);

const User = mongoose.model("User", userSchema);
module.exports = User;

【问题讨论】:

【参考方案1】:

在尝试匹配密码之前,您是否确保后端正确接收了电子邮件和密码?

我认为问题出在这里:

const config = 
      headers: 
        "Content-Type": "appllication/json",
      ,
    ;

由于“appllication/json”不是一个有效的 Content-Type,它没有像它应该的那样被解析。尝试删除“l”。

【讨论】:

感谢您的快速回复。抱歉,我无法理解我应该删除哪些内容,请您详细说明一下。 在上述代码中,将“appllication/json”替换为“application/json”。

以上是关于POST 请求失败,无法登录的主要内容,如果未能解决你的问题,请参考以下文章

无法打开登录请求的数据库“”。登录失败。用户“sa”登录失败

实体框架无法打开登录请求的数据库 - 用户登录失败

无法打开登录请求的数据库“ASPNETDB”。登录失败。用户 'Philip-Desktop\Philip' 登录失败

无法打开登录请求的数据库 MyDB。登录失败。用户“myUser”的登录失败

无法使用赛普拉斯发送 POST 登录请求

无法打开登录请求的数据库“ABC”。登录失败