Cannot parse to get the token - node.js

For some reason I cannot get the token from the localstorage in order to make the request, it says that there is no token. I am using cookie parser. I am trying to create a new category for my shop. It is not recognizing the token, although it is here.
here is my client:
adminDashoard.js
import { useState } from 'react';
import { createCategory } from './api/category';
import isEmpty from 'validator/lib/isEmpty';
import { showErrorMsg, showSuccessMsg } from './helpers/message';
import { showLoading } from './helpers/Loading'
export default function AdminDashboard() {
const [category, setCategory] = useState('');
const [errorMsg, setErrorMsg] = useState('');
const [successMsg, setSuccessMsg] = useState('');
const [loading, setLoading] = useState(false);
const handleMessages= evt =>{
setErrorMsg('');
setSuccessMsg('');
}
const handleCategoryChange = (evt) => {
setErrorMsg('');
setSuccessMsg('');
setCategory(evt.target.value);
}
const handleCategorySubmit = (evt) => {
evt.preventDefault();
if (isEmpty(category)) {
setErrorMsg('Please enter a category')
} else {
const data = { category }
setLoading(true);
createCategory(data)
.then(response => {
setLoading(false);
setSuccessMsg(response.data.successMessage)
})
.catch(err => {
setLoading(false);
setErrorMsg(err.response.data.errorMessage)
console.log(err)
})
}
};
function ShowHeader() {
return (
<div className='bg-dark text-white py-4'>
<div className='container'>
<div className='row'>
<div className='col-md-6'>
<h1>
<i className='fas fa-home'> Dashboard</i>
</h1>
</div>
</div>
</div>
</div>
)
}
function ShowActionBtns() {
return (
<div className='bg-light my-2'>
<div className='container'>
<div className='row pb-3'>
<div className='col-md-4 my-1 '>
<button
className='btn btn-outline-info btn-block'
data-toggle='modal'
data-target='#addCategoryModal'>
<i className=' fas fa-plus'>Add Category</i>
</button>
</div>
<div className='col-md-4 my-1 '>
<button className='btn btn-outline-danger btn-block'>
<i className=' fas fa-plus'>Add Products</i>
</button>
</div>
<div className='col-md-4 my-1 '>
<button className='btn btn-outline-success btn-block'>
<i className=' fas fa-plus'>Add Blog</i>
</button>
</div>
</div>
</div>
</div>
)
}
function ShowCategoryModal() {
return (
<div id='addCategoryModal' className='modal' onClick={handleMessages}>
<div className='modal-dialog modal-dialog-centered modal-lg'>
<div className='modal-content'>
<form onSubmit={handleCategorySubmit}>
<div className='modal-header bg-info text-white'>
<h5 className='modal-title'>Add Category</h5>
<button className='close' data-dismiss='modal'>
<span>
<i className='fas fa-times'></i>
</span>
</button>
</div>
<div className='modal-body my-2'>
{errorMsg && showErrorMsg(errorMsg)}
{successMsg && showSuccessMsg(successMsg)}
{
loading ? (
<div className='text-center'>{showLoading()}</div>
) : (
<>
<label className='text-secondary'> Category</label>
<input
type='text'
className='form-control'
name='category'
value={category}
onChange={handleCategoryChange}
/>
</>
)
}
</div>
<div className='modal-footer'>
<button data-dismiss='modal' className='btn btn-secondary'>Close</button>
<button className='btn btn-info' type='submit'>Submit</button>
</div>
</form>
</div>
</div>
</div>
)
}
return <div>
{ShowHeader()}
{ShowActionBtns()}
{ShowCategoryModal()}
</div>
}
Here is my api file:
import axios from "axios"
export const createCategory = async (formData) => {
const config = {
headers: {
'Content-Type': 'application/json'
},
};
const response = await axios.post('http://localhost:5000/api/category', formData, config);
return response;
}
on the server side,
here is my server.js :
const express=require('express');
const app= express();
const cors=require('cors');
const connectDB= require('./database/db');
const morgan= require('morgan');
const authRoutes= require ('./routes/auth')
const categoryRoutes = require ('./routes/category');
const cookieParser = require('cookie-parser')
//middleware
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
app.use(cookieParser());
app.use('/api/auth', authRoutes);
app.use('/api/category', categoryRoutes);
connectDB();
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));
app.get('/', (req, res) =>{
res.send(' hello server')
})
here is my route file :
const express = require('express');
const router = express.Router();
const categoryController = require('../routes/controllers/category');
const {authenticatateJWT} = require('./middleware/authenticator');
router.post('/', authenticatateJWT, categoryController.create);
module.exports = router;
here is my controller:
exports.create = (req, res)=>{
console.log(req.user);
setTimeout(() =>{
res.json({
successMessage: `${req.body.category} was created!`
});
}, 5000)
}
here is my middleware:
const jwt = require('jsonwebtoken');
const { jwtSecret } = require('../../config/keys');
exports.authenticatateJWT = (req, res, next) => {
const token = req.cookies.token;
console.log(token);
if (!token) {
return res.status(401).json({
errorMessage: 'No token. Authorization denied',
});
}
try {
const decoded = jwt.verify(token, jwtSecret);
req.user = decoded.user;
next();
} catch (err) {
console.log('jwt error:', err)
res.status(401).json({
errorMessage: 'Invalid token',
});
}
};

Related

What did I do wrong when I push database registers to Json-server to users.json. I have 404 not found

I am new to ReactJs coding, I have watched some videos about fake JSON-Server, but I don't know how to post all data from register.js to my "users.json" through "server.js".
What I do is I have an edit "package.json" "script": "auth": "node server.js" and npm i json-server, npm i json-server jsonwebtoken body-parser --save-dew and npm run auth to run server.js
I learn this on youtube...
Here is my source code. Someone can fix my wrong "post", Thank you!
users.json
{
"users": [
{
"id": 1
"username":"admin",
"email": "123#gmail.com",
"phone": "01234",
"pass": "admin1234",
"gender":"female",
"role":"shop"
}
]
}
server.js
const fs = require("fs");
const bodyParser = require("body-parser");
const jsonServer = require("json-server");
const jwt = require("jsonwebtoken");
const server = jsonServer.create();
const userdb = JSON.parse(fs.readFileSync("./database/users.json", "utf-8"));
server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());
server.use(jsonServer.defaults());
const SECRET_KEY = "85423112"; //*random key to see access-token
const expiresIn = "1h";
function createToken(payload) {
return jwt.sign(payload, SECRET_KEY, {expiresIn});
}
function isLoginAuthenticated({username, password}) {
return (
userdb.users.findIndex((user) => user.username === username && user.pass === password) !== -1
); ư
}
function isSignupAuthenticated({username}) {
return (
userdb.users.findIndex((user) => user.username === username ) !== -1);}
server.post("api/auth/register", (req,res)=>{
const {username,email,phone,password, gender,role} = req.body;
if(isSignupAuthenticated({username})){
const status = 401;
const message = "Username already taken";
res.status(status).json({status,message}) //*taken err will appeare in web console
return;
}
fs.readFile(".database/users.json", (err, data) => {
if(err){
const status = 401;
const message = "err";
res.status(status).json({status,message}) //*err when read file in system will appeare in web console
return;
}
data = JSON.parser(data.toString());
let last_item_id = data.users[data.user.length - 1].id;
data.users.push({id: last_item_id +1, username:username,email:email,phone: phone, pass:password, gender:gender, role:role });
let writeData = fs.writeFile("./database/users.json", JSON.stringify(data), (err, result)=>{
if (err) {
const status = 401;
const message = "err";
res.status(status).json({status,message})
return;
}
});
});
const access_token = createToken({username,password});
res.status(200).json({access_token}); //* set status to be OKKKKK when create account success =)))
});
server.post("/api/auth/login", (req,res)=>{
const {username,password} = req.body;
if(!isLoginAuthenticated({username,password})){
const status = 401;
const message = "Incorrect Username or Password";
res.status(status).json({status,message}) //*wrong will appeare in web console
return;
}
const access_token = createToken({username,password});
res.status(200).json({access_token}); //* set status to be OKKK when login ok =)))
});
server.listen(5001, ()=>{
console.log("running json api server");
});
Register.js
import React, {useState} from 'react'
import '../styles/Signup.css'
import axiox from "axios";
import {useHistory, Link} from 'react-router-dom'
import VisibilityIcon from '#mui/icons-material/Visibility'
import VisibilityOffIcon from '#mui/icons-material/VisibilityOff'
function Register() {
const [username,setUsername]= useState("");
const [password,setPassword]= useState("");
const [email,setEmail]= useState("");
const [phone,setPhone]= useState("");
const [gender,setGender]= useState("");
const [role,setRole]= useState("");
const [error, setError]= useState("");
let history = useHistory();
const [showPass,setshowPass]= useState(false);
const [showconfirmPass,setshowconfirmPass]= useState(false);
const register = (e) => {
e.preventDefault();
axiox.post("http://localhost:5001/api/auth/register",
{username,
email,
phone,
password,
gender,
role,
}).then((response)=> {
console.log("response", response)
localStorage.setItem("login", JSON.stringify({
userLogin: true,
token: response.data.access_token,
}));
setError("");
setUsername("");
setEmail("");
setPhone("");
setPassword("");
setGender();
setRole();
history.push("/login");
}).catch(error =>setError(error.response.data.message));
};
return (
<div>
<div id="getstarted">Get started</div>
<div id="intro"><span>Sign up</span> to our website and start to explore your unique style today !</div>
<div class="center">
<form onSubmit={register}>
<div class="txt_field">
<input type="text" required
value={username}
onChange={(e)=> setUsername(e.target.value)}/>
<span></span>
<label>Username</label>
</div>
<div class="txt_field">
<input type="text" required
value={email}
onChange={(e)=> setEmail(e.target.value)}/>
<span></span>
<label>Email</label>
</div>
<div class="txt_field">
<input type="text" required
value={phone}
onChange={(e)=> setPhone(e.target.value)}/>
<span></span>
<label>Phone number</label>
</div>
<div class="txt_field">
<input type={showPass ?"text":"password" }required
value={password}
onChange={(e)=> setPassword(e.target.value)}/>
<span></span>
<label>Password</label>
</div>
<div class="password1" onClick={()=>{if(showPass == true){setshowPass(false)}else {setshowPass(true)}}}>
{showPass ? <VisibilityIcon/> : <VisibilityOffIcon/>}
</div>
<div class="txtfield_1">
<input type={showconfirmPass ?"text":"password" } required/>
<span></span>
<label>Confirm Password</label>
</div>
<div class="confirm" onClick={()=>{if(showconfirmPass == true){setshowconfirmPass(false)}else {setshowconfirmPass(true)}}}>
{showconfirmPass ? <VisibilityIcon/> : <VisibilityOffIcon/>}
{error && <p2 style={{
color:"red",
position:"absolute",
top:"580px", width:"500px", left:"15vw"
}}>{error}</p2>}
</div>
<div id="general">
<div class="signup_link">
Already have an account? <Link to="/login">Sign in</Link>
</div>
<input type="submit" value="Learn More"/>
</div>
</form>
</div>
<div id="rightside">
<div id="sex">Sex</div>
<div id="button">
<input type="radio" name="gender" value={gender =="male"} onChange={(e)=> setGender(e.target.value)}/>
<label for="male"></label>
<span>Male</span>
<input type="radio" name="gender" value={gender =="female"} onChange={(e)=> setGender(e.target.value)}/>
<label for="female"></label>
<span>Female</span>
</div>
<div class="rect1">
<button class="button" type="button" value={role == "shop"} onChange={(e)=> setRole(e.target.value)}><img src={process.env.PUBLIC_URL + `/Images/shop 1.png`} /></button>
</div>
<div class="rect2">
<button class="button" type="button" value={ role == "customer"} onChange={(e)=> setRole(e.target.value)}> <img src={process.env.PUBLIC_URL + `/Images/take-away.png`} /></button>
</div>
</div>
</div>
);
}
export default Register
You should change your route from server.post("api/auth/register", (req,res)=>{ to server.post("/api/auth/register", (req,res)=>{ in server.js file

how to solve this Cannot POST error in MERN?

I am inserting two images along with the form data into MongoDB database.
While both images are stored in my pc folder but all form data isn't uploading in the database.
error
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /</pre>
</body>
</html>
in my console. Please help me how to solve that.
I have tried some previously asked question in stackOF.
app.js
const express = require("express")
const app = express()
const cors = require('cors');
const env = require("dotenv")
const port = 5000
env.config({path: "../server/config.env"})
require("../server/db/conn")
app.use(cors());
app.use(express.json())
app.use(require("../server/router/auth"))
app.listen(port, (err) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
module.exports = "conn"
register.js(frontend)
const Register = () => {
const [newUser, setNewUser] = useState({
school: "",
address: "",
photo: "",
photoone: ""
});
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("school", newUser.school);
formData.append("photo", newUser.photo);
formData.append("photoone", newUser.photoone)
formData.append("address", newUser.address);
axios({
method: "post",
url: "/teacher",
data: formData,
headers: { "Content-Type": "multipart/form-data" },
})
.then((response) => {
console.log(response)
}).then((data) => {
console.log(data)
}).catch((error) => {
if (error.response) {
console.log(error.response.data)
}
})
};
const handleChange = (e) => {
setNewUser({ ...newUser, [e.target.name]: e.target.value });
};
const handlePhoto = (e) => {
setNewUser({ ...newUser, photo: e.target.files[0] });
};
const handlePhotoone = (e) => {
setNewUser({ ...newUser, photoone: e.target.files[0] });
};
return (
<>
<div className="container main">
<div className="row">
<div className="col-sm-6 col-md-6 col-lg-6">
<form onSubmit={handleSubmit} encType="multipart/form-data">
<div class="mb-3">
<label class="form-label">
Your school
</label>
<input
type="text"
class="form-control"
id="exampleInputPassword1"
id="school"
name="school"
value={newUser.school}
onChange={handleChange}
/>
</div>
<div class="input-group mb-3">
<input
type="file"
id="pic"
accept=".png, .jpg, .jpeg"
name="photo"
onChange={handlePhoto} type="file" class="form-control" id="inputGroupFile02" />
</div>
<div class="input-group mb-3">
<input
type="file"
id="pic"
placeholder="second photo"
accept=".png, .jpg, .jpeg"
name="photoone"
onChange={handlePhotoone} type="file" class="form-control" id="inputGroupFile01" />
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">
your address
</label>
<input
type="text"
id="address"
name="address"
value={newUser.address}
onChange={handleChange}
class="form-control"
aria-describedby="emailHelp"
/>
</div>
<button
value="register"
type="submit"
class="btn btn-primary"
>
Submit
</button>
</form>
</div>
</div>
</div>
</>
);
};
auth.js(backend)
const mongoose = require("mongoose")
const express = require("express")
const router = express()
require("../db/conn")
const User = require("../model/userSchema")
const Teacher = require("../model/userSchemaTeacher")
const multer = require('multer');
let path = require('path');
let fs = require("fs-extra");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
let schoolname = req.body.school;
let path = `C:/Users/kumar/Desktop/mern/server/images/${schoolname}`;
fs.mkdirsSync(path);
cb(null, path);
// cb(null, 'images');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
const fileFilter = (req, file, cb) => {
const allowedFileTypes = ['image/jpeg', 'image/jpg', 'image/png'];
if (allowedFileTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(null, false);
}
}
let upload = multer({ storage, fileFilter });
router.route('/teacher').post(upload.fields([{
name: "photo", maxCount: 1
}, {
name: "photoone", maxCount: 1
}
])), (req, res) => {
const school = req.body.school;
const photo = req.file.filename
const photoone = req.file.filename
const address = req.body.address;
const newUserData = {
school,
photo,
photoone,
address,
}
const newUser = new Teacher(newUserData);
newUser.save()
.then(() => res.json('User Added'))
.catch((err) => {
console.log(err);
});
}
Please see how to solve that?
The route you are trying to POST your form data is not defined please set your route path like this:
router.post('/teacher',upload.fields([{
name: "photo", maxCount: 1
}, {
name: "photoone", maxCount: 1
}
]), (req, res) => {
const school = req.body.school;
const photo = req.files['photo'][0]
const photoone = req.files['photoone'][0]
const address = req.body.address;
const newUserData = {
school,
photo,
photoone,
address,
}
const newUser = new Teacher(newUserData);
newUser.save()
.then(() => res.json('User Added'))
.catch((err) => {
console.log(err);
});
})
...

Upload image with Multer and Formik to Mongodb (MERN)

I created app using MERN.
Now I'm trying to upload image with Multer and Formik, but req.file returns undefined, and I can't understand why.
I'm new in this, but I guess this may cause from JSON.stringify (http.hook) or content-type: application/json. I also tried do this with FormData, but that's not working. Any ideas?
UPDATE: With Postman works good. I think problem is in ui part, input doesn,t pass the file.
app.js
const {Router} = require('express');
const multer = require('multer');
const auth = require('../middleware/auth.middleware');
const Users= require('../models/Users');
const router = Router();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './client/public/uploads/');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const upload = multer({
storage: storage,
limits: { fileSize: 10 * 1024 * 1024 }
});
router.post('/create', upload.single('image'), auth, async (req, res) => {
console.log(req.file);
try {
const code = req.body.code;
const existing = await Users.findOne({code: code});
if(existing) {
return res.json({user: existing})
}
const user = new Users(req.body);
await user .save();
res.status(201).json(user);
} catch (e) {
console.log(e);
res.status(500).json({ message: 'Error: try again.' })
}
});
http.hook.js
import {useState, useCallback} from 'react';
export const useHttp = () => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const request = useCallback(async (url, method = 'GET', body = null, headers = {}) => {
setLoading(true);
try {
if(body) {
body = JSON.stringify(body);
headers['Content-Type'] = 'application/json';
}
const response = await fetch(url, {method, body, headers});
const data = await response.json();
if(!response.ok) {
throw new Error(data.message || 'Something goes wrong')
}
setTimeout(() => {
setLoading(false);
}, 800);
return data
} catch (e) {
setLoading(false);
setError(e.message);
throw e;
}
}, []);
const clearError = useCallback(() => {setError(null)}, []);
return {loading, request, error, clearError}};
CreateUser.js
import React, {useCallback, useContext, useEffect, useState} from 'react';
import {useHttp} from "../hooks/http.hook";
import Button from "../components/Button/Button";
import {AuthContext} from "../context/auth.context";
import {Formik} from "formik";
export const CreateUser = () => {
const {token} = useContext(AuthContext);
const {loading, request} = useHttp();
const createUser = useCallback(async (body) => {
try {
const fetched = await request(`/api/user/create`, 'POST', body, {
Authorization: `Bearer ${token}`
});
} catch (e) {console.log(e)}
}, []);
const handleCreate = (values, {resetForm}) => {
console.log(values);
createUser(values);
// resetForm({});
};
return (
<div className="wrapper">
<div className="row">
<div className="column small-12 text-center color-white mb_45">
<div className="custom-headline text text-48 font-bold">
<h1>
Crate user
</h1>
</div>
</div>
</div>
<Formik
enableReinitialize
initialValues={{
name: '',
code: '',,
image: null
}}
onSubmit={handleCreate}
>
{({
values,
errors,
touched,
handleBlur,
handleChange,
handleSubmit,
isSubmitting,
setFieldValue,
resetForm
}) => (
<form onSubmit={handleSubmit} className="row align-center">
<div className="column small-12 large-7">
<div className="form-item flex-container align-middle mb_20">
<label className="text text-14 font-semibold font-uppercase text-right small-4">
Photos
</label>
<input id="image" type="file" name="image" className="file_input"
onChange={(event) => {
setFieldValue("image", event.currentTarget.files[0]);
}} />
</div>
</div>
<div className="column small-12 large-7">
<div className="form-item flex-container align-middle mb_20">
<label className="text text-14 font-semibold font-uppercase text-right small-4">
Name
</label>
<input
className="text text-17 "
type="text"
name="name"
onChange={handleChange}
onBlur={handleBlur}
value={values.name}
/>
</div>
</div>
<div className="column small-12 large-7">
<div className="form-item flex-container align-middle mb_20">
<label className="text text-14 font-semibold font-uppercase text-right small-4">
Code
</label>
<input
className="text text-17"
type="text"
name="code"
onChange={handleChange}
onBlur={handleBlur}
value={values.code}
/>
</div>
</div>
<div className="column small-12 mt_20">
<div className="btn_group flex-container flex-wrap align-middle align-center">
<Button className="btn-lg radius-8" theme="blue"
text={Submit} type="submit"
/>
</div>
</div>
</form>
)}
</Formik>
</div>
)
};
Wrap out your image file with formData with the multer key "image"
upload.single('image')
on Front-End
const handleCreate = async (values) => {
try {
const body = new FormData();
body.append( "image", values.image);
...
} catch (err) {}
};
And make sure about your destination path use "dirname"
`${__dirname}/../client/public/uploads/`
Change this according to your directory path
OK! I don't know WHY this was cause, but I found solution - I use axios instead of fetch, and of course FormData for uploading images or files, and it works!
Hope this may be helpful for someone else. Thanks for all answers.
const handleCreate = (values, {resetForm}) => {
const formData = new FormData();
formData.append('name', values.name);
formData.append('code', values.code);
formData.append('image', values.image);
axios.post('/api/user/create', formData)
.then(console.log)
catch(console.error);
resetForm({});
};
I have 2-3 suggestion,
in your app.js file
router.post('/create', upload.single('image'), auth, async (req, res) => {
console.log(req.file);
you should use auth middelware before using upload.single.
and you should send headers with POST request with {content type: multipart/form-data}

Why did it failed to load? the server responded with a status of 404 (Not Found)

I have my app(express+Next.js.MOngoDB).I signuped all my users,works Ok. Now when I try signin
http://localhost:5000/signin
I got error
Uncaught (in promise) Error: Request failed with status code 404
at createError (webpack-internal:///../../node_modules/axios/lib/core/createError.js:16)
at settle (webpack-internal:///../../node_modules/axios/lib/core/settle.js:17)
Terminal
GET /__nextjs_original-stack-frame?isServerSide=false&file=webpack-internal%3A%2F%2F%2F..%2F..%2
POSTMAN signin works fine
app.js(just API)
const app = express();
app.use('/api/v1/auth', auth);
Next.js,Signin
import SigninComponent from '../components/frontauth/SigninComponent';
const Signin = () => {
return (
<Layout>
<h2 className="text-center pt-3 pb-4">Signin</h2>
<div className="row">
<div className="col-md-6 offset-md-3">
<SigninComponent />
</div>
</div>
</Layout>
);
};
SigninComponent
/* eslint-disable no-undef */
import axios from 'axios';
import React, { useState } from 'react';
import { API } from '../../config';
const SigninComponent = () => {
const [values, setValues] = useState({
email: '',
password: ''
});
const [loading, setLoading] = useState(false);
const { email, password } = values;
const handleSubmit = async (e) => {
e.preventDefault();
const { email, password } = values;
const user = { email, password};
await axios.post(`${API}/api/v1/auth/signin`, user);
};
const handleChange = name => e => {
setValues({ ...values, error: false, [name]: e.target.value });
};
const showLoading = () => (loading ? <div className="alert alert-info">Loading...</div> : '');
const signinForm = () => {
return (
<form onSubmit={handleSubmit}>
<div className="form-group">
<input
value={values.email}
onChange={handleChange('email')}
type="email"
className="form-control"
placeholder="Type your email"
/>
</div>
<div className="form-group">
<input
value={values.password}
onChange={handleChange('password')}
type="password"
className="form-control"
placeholder="Type your password"
/>
</div>
<div>
<button className="btn btn-primary">Signin</button>
</div>
</form>
);
};
return <React.Fragment>
{showLoading()}
{signinForm()}
</React.Fragment>;
};
export default SigninComponent;
How should I edit .babelrc,I have only one line,should I add plugins?
"presets": ["next/babel"]
Why does the terminal point to SSR FALSE?

Cannot POST /Admin

I was connecting react with my api in node js, but when connecting to the login the only thing that appears is "Cannot POST / Admin"
I have used the Postman and it seems that the back part works because the token returns, but I think there is some problem in the connection between the two.
I am working on react, nodejs, redux and mongodb
interface IProps {}
interface IPropsGlobal {
setToken: (t: string) => void;
setName: (u: string) => void;
}
const Login: React.FC<IProps & IPropsGlobal> = props => {
const [username, setUsername] = React.useState("");
const [password, setPassword] = React.useState("");
const [error, setError] = React.useState("");
const updateUsername = (event: React.ChangeEvent<HTMLInputElement>) => {
setUsername(event.target.value);
setError("");
};
const updatePassword = (event: React.ChangeEvent<HTMLInputElement>) => {
setPassword(event.target.value);
setError("");
};
const signIn = () => {
fetch("http://localhost:3006/api/auth", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: username,
password: password
})
})
.then(response => {
if (response.ok) {
response
.text()
.then(token => {
console.log(token);
props.setToken(token);
props.setName(username);
});
} else {
setError("Usuario o Contraseña incorrectos");
}
})
.catch(err => {
setError("Usuario o Contraseña incorrectos.");
});
};
return (
<div>
<div className="section"></div>
<h5 className="indigo-text">Please, login into your account</h5>
<div className="section"></div>
<div className="container">
<div className="z-depth-1 grey lighten-4 row er" >
<form className="col s12" method="post">
<div className='row'>
<div className='col s12'>
</div>
</div>
<div className='row'>
<div className='input-field col s12'>
<input className='validate' name='email' id='email' value={username}
onChange={updateUsername}/>
<label >Enter your email</label>
</div>
</div>
<div className='row'>
<div className='input-field col s12'>
<input className='validate' type='password' name='password' id='password' value={password}
onChange={updatePassword} />
<label >Enter your password</label>
</div>
<label >
<a className='pink-text' href='#!'><b>Forgot Password?</b></a>
</label>
</div>
<br />
<div className='row'>
<button type='submit' name='btn_login' className='col s12 btn btn-large waves-effect indigo'
onClick={signIn}>Login</button>
</div>
</form>
</div>
</div>
Create account
</div>
);
};
const mapDispatchToProps = {
setToken: actions.setToken,
setName: actions.setName
};
export default connect(
null,
mapDispatchToProps
)(Login);
Postman returns the token
The api console shows me:
POST /api/auth - - ms - -
Connected successfully to server
In the Web page
Failed to load resource: the server responded with a status of 404 (Not Found)
I have used this code or a similar one before in other projects but I do not understand what happened to me this time
const md5 = require('md5');
// Connection URL
const mongoUrl = 'mongodb://localhost:27017';
// Database Name
const mongoDBName = 'ArdalesTur';
/* GET users listing. */
router.get('/', (req, res) => {
res.send('respond with a resource');
});
const secret = 'mysecret';
// para interactuar con la base de datos
router.post('/auth', (req, res) => {
mongo.MongoClient.connect(mongoUrl, (err, client) => {
assert.equal(null, err);
console.log('Connected successfully to server');
const db = client.db(mongoDBName);
const query = db.collection('Admin').find({
username: req.body.username,
password: md5(req.body.password),
});
query.toArray().then((documents) => {
if (documents.length > 0) {
const token = jwt.sign(
{
_id: documents[0]._id,
username: documents[0].username
},
secret,
// {
// expiresIn: 86400
// }
);
res.send(token);
} else {
res.status(400).send('Invalid credentials');
}
});
client.close();
});
});
here you have the api

Resources