当前在创建登录功能时遇到问题。每当我提交凭据时,我都会继续收到401响应。检查错误消息后,我在用户服务功能的登录功能中看到了错误。
我已经检查了项目的不同区域,即BASE_URL导致关联的路由,从而导致了我的用户控制器的关联模型。我清理了所有错字。我还通过控制台记录了可以给我更多信息的任何区域
//Login.jsx
//The following code, was presented, in the console.
import React, {Component} from 'react'
import { Link } from 'react-router-dom'
import userService from '../utils/userServices'
handleSubmit = async (e) => {
e.preventDefault();
try {
await userService.login(this.state);
console.log(userService.login())
this.props.handleSignupOrLogin();
this.props.history.push('/');
} catch(err){
console.log(err + "login err")
console.log('Invalid Credentials');
}
//TODO check to see if passing a history prop will work
}
//userServices.jsx
//res.ok returned false
import tokenService from './tokenServices';
function login(creds){
return fetch(BASE_URL + 'login',{
mode:'cors',
method: 'POST',
headers: new Headers({'Content-Type': 'application/json'}),
body: JSON.stringify(creds)
})
.then(res => {
console.log(res)
console.log(fetch)
if(res.ok) return res.json();
console.log(res.ok)
throw new Error('Bad Credentials');
})
.then(({ token }) => {tokenService.setToken(token)});
}
//routes/users.js
const express = require('express');
const router = express.Router();
const userCtrl = require('../controllers/user');
//public routes
router.post('/signup', userCtrl.signup)
router.post('/login', userCtrl.login)
module.exports = router;
//controllers/user.js
const User = require('../models/user');
const jwt = require('jsonwebtoken');
const SECRET = process.env.SECRET;
...
async function login(req, res) {
try {
const user = await User.findOne({username: req.body.username});
if (!user) return res.status(401).json({err: 'bad credentials'});
console.log(user)
user.comparePassword(req.body.password, (err, isMatch) => {
if (isMatch) {
const token = createJWT(user);
res.json({token});
} else {
return res.status(401).json({err: 'bad credentials'});
}
});
} catch (err) {
console.log(err)
return res.status(401).json(err);
}
}
The expected output
here Response
`{
type: "basic",
url:"http://localhost:3000/routes/users/login",
redirected: false,
status: 401,
ok: true,
…}
`
but instead got
Response {
`type: "basic",
url: "http://localhost:3000/routes/users/login",
redirected: false,
status: 401,
ok: false,
…}`