JWT client server connection not found - javascript

error image
Server Site
Getting Email query from server site, It's not connecting to my client site But it's working on my server site
app.get('/login', async (req, res) => {
const user = req.body;
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: '1d'
});
res.send({ accessToken });
});
Client Ste Login Function Part
This is my client site login part functional and callback part, There my email is showing in console but doesn't work in server which I show in picture.
import axios from 'axios';
import React from 'react';
import { useAuthState, useSignInWithEmailAndPassword } from 'react-firebase-hooks/auth';
import GoogleButton from 'react-google-button';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import auth from '../Firebase.init';
const Login = () => {
const navigate = useNavigate();
const [signInWithEmailAndPassword, loading, error] = useSignInWithEmailAndPassword(auth);
const [user] = useAuthState(auth);
if (user) {
navigate('/');
}
const handleLogin = async e => {
alert('ok');
e.preventDefault();
const email = e.target.email.value;
const password = e.target.password.value;
await signInWithEmailAndPassword(email, password);
const { data } = await axios.post('http://localhost:5000/login', { email })
console.log(data);
console.log(email);
};
}

Related

React axios.get 401 unauthorized

I used the postman for testing my url,and it has response data(It's correct).
Url:http://localhost:8000/api/products/find/6337d5d73ec2c05d7c11bc63(ProductId).
In postman,it could get response data.
I wonder I do give it Bearer token in my requestMethods.js,which imported in /pages/Product.jsx.
But when I use the same id in axios.get,it said error:
Error:GET http://localhost:8000/api/products/find/6337d5d73ec2c05d7c11bc63 401 (Unauthorized)
can someone just help me solve this question?
In /pages/product.jsx line 145,157 are got tag in the photo.
Here are my relative Codes:
requestMethods.js
import axios from "axios";
const BASE_URL = "http://localhost:8000/api/"
const TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9......"
export const publicRequest = axios.create({
baseURL: BASE_URL,
});
export const userRequest = axios.create({
baseURL: BASE_URL,
headers: { token: `Bearer ${TOKEN}` },
});
/pages/Product.jsx
It's mainly codes of website.
import { useLocation } from 'react-router-dom'
import { useState, useEffect } from 'react';
import { publicRequest,userRequest } from './requestMethods';
const Product = () => {
// 回傳路徑
const location = useLocation();
const id = location.pathname.split("/")[2];
const [product, setProduct] = useState({});
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get("/products/find/" + id);//HERE USE REQUESTMETHODS.JS and it's it sad line:145
console.log(res.data)
setProduct(res.data);
}
catch { } }
getProduct();//line 157
}, [id])
}
export default Product
index.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const userRouter = require("./routes/user");
const authRouter = require("./routes/auth");
const productRouter = require("./routes/product");
const cors=require("cors");
dotenv.config();
mongoose.connect(
process.env.MONGO_URL)
.then(() => console.log("connect"))
.catch(((err) => {
console.log(err);
}));
app.use(express.json());
app.use(cors());
app.use("/api/users", userRouter);
app.use("/api/auth", authRouter);
app.use("/api/products", productRouter);//USE THE ROUTES/PRODUCT.JS
app.use("/api/orders", orderRouter);
app.use("/api/cart", cartRouter);
app.use("/api/checkout",stripeRouter)
app.listen(process.env.PORT || 8000, () => {
console.log("Run server")
})
routes/product.js
router.put("/:id", verifyTokenAndAdmin, async (req, res) => {
try {
const updatedProduct = await Products.findByIdAndUpdate(req.params.id, {
$set: req.body
}, { new: true }
);
res.status(200).json(updatedProduct);
} catch (err) {
res.status(500).json(err);
}
});
//delete
router.delete("/:id", verifyTokenAndAdmin, async (req, res) => {
try {
await Products.findByIdAndDelete(req.params.id);
res.status(200).json("Products has been deleted.")
} catch (err) {
res.status(500).json(err);
}
})
//get product
router.get("/find/:id", verifyTokenAndAdmin, async (req, res) => {
try {
const product = await Products.findById(req.params.id);
res.status(200).json(product);
} catch (err) {
res.status(500).json(err);
}
})
verifyToken.js
const jwt = require("jsonwebtoken");
const verifyToken = (req, res, next) => {
const authHeader = req.headers.token;
if (authHeader) {
const token = authHeader.split(" ")[1];
jwt.verify(token, process.env.JWT_SEC, (err, user) => {
if (err)
res.status(401).json("Token is not valid!")
req.user = user;
next();
})
}
else {
return res.status(401).json("You are not authentication!" );
}
}
module.exports = { verifyToken, verifyTokenAndAuth, verifyTokenAndAdmin };
The reason is you are using publicRequest axios function which does not include bearer token header. Use userRequest function.
Try using the code below in your axios request from frontend:
const res = await userRequest.get("/products/find/${id}");
Instead of double quotes use string literal. Stack overflow is using my string literal as code snippet that's why I wrote in double quotes.
Also remove the extra slash after api from BASE_URL like this:
const BASE_URL = "http://localhost:8000/api"
Also check in your verifyToken.js file if you have written the functions verifyTokenAndAuth and verifyTokenAndAdmin which you are exporting. If not then please write those functions in verifyToken.js file and then export because you are using verifyTokenAndAdmin middleware in your api. Also please check that server is running and not crashing before making a request.

I am receiving a "User.findOne is not a function" error message despite this same model working in another file. Similar question answers didn't work

First time posting on here, FYI.
Below is my "User" model in its own file. I create the schema and assign it. When I go to use this model in my authRoutes file it works fine just as you'd imagine. But when I use an identical import in one of my screen files I receive the "User.findOne is not a function" error message (linked below).
I am using this method to find a user in the database in order to access it's attributes. I have tried using the module.exports way of exporting the model and also trying to use require() as the import statement...neither has fixed my issue...been stuck on this for a while some insight would be great! (Hopefully this was clear, let me know)
"User.findOne is not a function..."
models/User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
balance: {
type: Number,
default: 100,
}
});
mongoose.model('userSchema', userSchema);
routes/authRoutes.js (Works here)
const mongoose = require('mongoose');
const User = mongoose.model('userSchema');
const express = require('express');
const router = express.Router();
//const User = require('../models/User');
const jwt = require('jsonwebtoken');
router.post('/signup', async (req, res) => {
const {email, password} = req.body;
try {
const user = new User({email, password});
await user.save();
const token = jwt.sign({ userId: user._id}, 'SOME_SECRET_KEY');
res.send({token});
} catch (err) {
return res.status(422).send(err.message);
}
});
router.post("/signin", async (req, res) => {
const {email, password} = req.body;
if (!email || !password) {
return res.status(422).send({error: "Must provide email and password."});
}
const user = await User.findOne({ email });
if (!user) {
return res.status(422).send({ error: "Invalid email or password"});
}
try {
//await user.comparePassword(password);
const token = jwt.sign({userId: user._id}, "SOME_SECRET_KEY");
res.send({token, email});
} catch (err) {
return res.status(422).send({ error: "Invalid email or password"});
}
})
screens/SomeScreen.js (Does NOT work here, error)
import React, {useContext, useState} from 'react'
import {View, StyleSheet, Text, ScrollView, TextInput, Button} from 'react-native';
//import { LinearGradient } from 'expo-linear-gradient';
import colors from '../../constants/colors';
import RecieverCard from '../../components/RecieverCard';
import HistoryCard from '../../components/HistoryCard';
import {Provider, Context} from "../context/AuthContext";
import AsyncStorage from "#react-native-async-storage/async-storage";
const mongoose = require('mongoose');
const User = mongoose.model('userSchema');
const getUserBalance = async (userEmail) => {
let user;
try {
user = await User.findOne(userEmail);
} catch(err) {
console.log(err);
}
return user;
};
require is not a React api, and so it will not work in your frontend.
You should use that in your node.js backend.
Regardless, why would you use mongoose & models in your frontend? I suggest you make an endpoint / controller responsible of getting the user balance in your backend, and then simply send a request to your backend and await for the response data.

Can't reach server, React 404 error 'Post'

I can't reach server side I checked everything it should work
error is:
"POST http://localhost:3000/ 404 (Not Found)"
Here is my code
On client side here, I call createPost at jsx file and in actions/post.js file:
import * as api from "../api/index";
import * as types from "./types";
export const createPost = (post) => async (dispatch) =>{
try {
const {data} = await api.createPost(post);
dispatch({
type: types.CREATE_POST,
payload: data,
});
} catch (error) {
console.log(error);
}
};
from here it should call the api,
import axios from "axios";
const apiEndpoint = "/";
export const fetchPosts = async () => await axios.get(apiEndpoint);
export const createPost = async (post) => await axios.post(apiEndpoint, post);
and from there to server side but there is a error at createPost first.
btw in server,
import express from "express";
import {getPosts, createPost} from "../contollers/posts.js";
const router = express.Router();
//localhost/posts
// GET POST DELETE UPDATE
router.get("/", getPosts);
router.post("/", createPost);
export default router;
and in controller:
export const createPost = async(req,res) => {
const post = req.body;
const newPost = new Post(req.body);
try{
await newPost.save();
res.status(201).json(newPost);
}catch(error){
res.status(409).json({
message: error.message,
});
}
};
thanks for help
yeah its my stupidity that correcting some router&dom versions and url to 5000(which is the server) solved the issue

Register route 404 not found

I am building a register page and when I submit the I am getting a 404 not found. I am using react and express and I think the front end is good. I am missing some back end or have the wrong url for my post request: axios.post('http://localhost:3000/auth'. Would appreciate some advice if anyone can see what I have wrong.
const handleSubmit = event => {
event.preventDefault();
const user = {
username: username,
password: password,
}
axios.post('http://localhost:5000/', { user })
.then(res=>{
console.log(res);
console.log(res.data);
})
}
This is the registerPost function for my route.
export const registerPost = async (req, res) => {
const {username, password} = req.body;
const newUser = new User({username, password});
try {
await newUser.save();
console.log(newUser);
res.status(201).json(newUser);
} catch (error) {
res.status(409).json({ message: error.message });
}
}
These are the routes.
import express from 'express';
import { getPosts } from '../controllers/posts.js'
import { createPost, updatePost, deletePost, registerPost } from '../controllers/posts.js'
const router = express.Router();
router.get('/', getPosts);
router.post('/', createPost);
router.patch('/:id', updatePost);
router.delete('/:id', deletePost);
router.post('/auth', registerPost);
export default router;
You're getting a 404 error, which means the url you're trying to reach does not exist. In the React app, you're sending the request at http://localhost:5000/, but in the Express app, you've defined the register route as /auth.
Updating the url in the React app to http://localhost:5000/auth should fix this.
As far as I can see you're passing the following Object from the Frontend:
{ user: { username, password } }
but in the backend you're not looking for the user property, but directly for the username and password.
const {username, password} = req.body
// =>
const { user } = req.body

Error 401 Unauthorized in Browser and Postman ok

Good morning people
I am setting up the front-end for testing, In my application I use Passport, Token Jwt for authentication. At Postman, everything is ok! I can authenticate myself.
Now in the Browser, I log in it generates the token, however when trying to execute a route protected by the passport it returns me unauthorized
Follow my code. I'm a beginner, first post on the stackoverflow.
Routes.js
app.route('/rifas')
.all(app.config.passport.authenticate())
.post(app.api.rifas.saverifa)
Passport.js
const authSecret = process.env.authSecret
const passport = require('passport')
const passportJwt = require('passport-jwt')
const { Strategy, ExtractJwt } = passportJwt
module.exports = app => {
const options = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: authSecret
}
const strategy = new Strategy(options,(payload, done) => {
app.db('users')
.where({id: payload.id})
.first()
.then( user => {
if(user) {
done(null, {id: user.id, email: user.email})
}
else {
done(null,false)
}
})
.catch(err => done(err,false))
})
passport.use(strategy)
return {
initialize: () => passport.initialize(),
authenticate: () => passport.authenticate('jwt', {session: false})
}
}
Archive api.js
import axios from 'axios'
const api = axios.create({
baseURL: 'localhost:3333',
})
export default api
Archive of front-end
async function handleLogin (e) {
e.preventDefault()
try {
const {data: token} = await axios.post('http://localhost:3333/signin', {
name: name,
email: email,
password: password
})
api.defaults.headers.Authorization = `Bearer ${token}`
window.location.href="http://localhost:3000/Header"
alert(`Logado com sucesso ${name}`)
}catch(e) {
alert('Erro no login')
}
}

Categories

Resources