Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

StackOverflow Point

StackOverflow Point Navigation

  • Web Stories
  • Badges
  • Tags
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Web Stories
  • Badges
  • Tags
Home/ Questions/Q 3862
Alex Hales
  • 0
Alex HalesTeacher
Asked: June 3, 20222022-06-03T04:31:10+00:00 2022-06-03T04:31:10+00:00

javascript – I have an express app deployed on Heroku but I have 404 (not found) error

  • 0

[ad_1]

everything works in my localhost:3000 and using a baseUrl of localhost:5000

I changed my baseUrl to the deployed site(https://mongodb-newsapi.herokuapp.com) but I got an error saying that my site is not found.

Failed to load resource: the server responded with a status of 404 (Not Found)
POST https://mongodb-newsapi.herokuapp.com/api/login 404 (Not Found)

this it my fetchDataApi:

import { axiosInstance } from './axios';

export const getDataApi = async (url, token) =>{

    const res = await axiosInstance.get(`/api/${url}`,{
        headers : {Authorization : token}
    })
    return res;
}

export const postDataApi =async (url, post, token) => {
   
    const res = await axiosInstance.post(`/api/${url}`, post ,{
        headers: {Authorization: token}

    })
    
    return res;
    
}

export const putDataApi = async (url , post, token) => {

    const res = await axiosInstance.put(`/api/${url}`,post,{
        headers :{Authorization: token}
    })
    return res;
}
export const patchDataApi = async (url , post, token) => {

    const res = await axiosInstance.patch(`/api/${url}`, post , {
        headers :{Authorization: token}
    })
    return res;
}
export const deleteDataApi = async (url , token) => {

    const res = await axiosInstance.delete(`/api/${url}`,{
        headers :{Authorization: token}
    })
    return res;
}

This is my baseUrl:

import axios from 'axios';

export const axiosInstance = axios.create({

    baseUrl: "https://mongodb-newsapi.herokuapp.com/api"
});

This is my server.js:

require('dotenv').config();

const path = require('path');

const express = require("express");

const mongoose = require('mongoose');

const cookieparser = require('cookie-parser');

const authRouter = require('./routers/authRouter');

const userRouter = require('./routers/userRouter');

const app = express();

app.use(express.json())

app.use(cookieparser());

app.use('/api', authRouter);

app.use('/api', userRouter);

app.use(express.static(path.join(__dirname, "/client/build")));

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '/client/build', 'index.html'));
});

I didn’t add the mongoose.connect because I have my account.

and this is the authCtrl:

const Users = require("../models/userModel");

const bcrypt = require('bcrypt');

const jwt = require('jsonwebtoken');

const authCtrl = {

    register: async (req, res) => {
        try {

            const { fullName, userName, email, password } = req.body;

            const newUsername = userName.toLowerCase().replace(/ /g, '');

            const user_name = await Users.findOne({ userName: newUsername })

            if(user_name) return res.status(400).json({ msg: 'This UserName Already Exist.' })

            const Email = await Users.findOne({ email: email })

            if(Email) return res.status(400).json({ msg: 'This Email Already Exist.' })

            if(password.length < 8) return res.status(400).json({ msg: 'Password must be atleast 8 Characters.' })

            const passwordHash = await bcrypt.hash(password, 15);

            const newUser = new Users({

                fullName, userName:newUsername, email, password:passwordHash
            })

            const access_token = createAccessToken({id: newUser._id});

            const refresh_token = createRefreshToken({id: newUser._id});

            console.log({access_token, refresh_token})

            res.cookie('refreshtoken', refresh_token, {
                httpOnly: true,
                path: "/api/refresh_token",
                maxAge: 24*30*60*60*1000
            })

            await newUser.save(); 
            
            res.json({
                msg: "Registered Success",
                access_token,
                user: {
                    ...newUser._doc,
                    password: ''
                }
            })

        } catch (error) {
            res.status(500).json({ msg: error.message })
        }
    },
    login: async (req, res) => {
        try {
        const {email , password} = req.body;

        const user = await Users.findOne({email})
        .populate("friends following" , "-password")

        if(!user) return res.status(400).json({msg: 'User does not exists'})

        const isMatch = await bcrypt.compare(password,user.password);
        if(!isMatch) return res.status(400).json({msg: 'User Password is incorrect'})

        const access_token= createAccessToken({id: user._id});
        const refresh_token= createRefreshToken({id: user._id});
        

        res.cookie('refreshtoken', refresh_token,{
            httpOnly: true,
            path:'/api/refresh_token',
            maxAge: 24*30*60*60*1000  
        })

        

        res.json({
            msg:"login sucess",
            access_token,
            user:{
            ...user._doc,
            password:''
            }
        })

    } catch (err) {
        return res.status(500).json({msg: err.message})
    }},logout: async ( req, res ) => {

        try {
            res.clearCookie('refreshtoken', {path: '/api/refresh_token'})

            res.json({msg: "Logged out"})

        } catch (error) {

        return res.status(500).json({ msg: error.message })
        }},generateAccessToken: async (req, res) => {

    try {
        const rf_token = req.cookies.refreshtoken;
            
           
        if(!rf_token) return res.status(400).json({msg:"please login now"})

        jwt.verify(rf_token, process.env.REFRESHTOKENSECRET, async(err,result)=>{
            if(err) return res.status(400).json({msg:"Please login now"})

            const user = await Users.findById(result.id).select("-password")
            .populate("friends following")

            if(!user) return res.status(400).json({msg:"user does not exist"})

            const access_token= createAccessToken({id: result.id});

            res.json({
                access_token,
                user
            })
            
        })
    } catch (error) {
        res.stauts(500).json({msg: error.message})
    }},}const createAccessToken = ( payload) =>{

    return jwt.sign(payload, process.env.ACCESSTOKENSECRET, {expiresIn: "1d"})}const createRefreshToken = ( payload) =>{

    return jwt.sign(payload, process.env.REFRESHTOKENSECRET,{expiresIn: "30d"})}module.exports = authCtrl

this the github repository:

https://github.com/Noobieprogrammer69/mongodb-heroku

[ad_2]

  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report
Leave an answer

Leave an answer
Cancel reply

Browse

Sidebar

Ask A Question

Related Questions

  • xcode - Can you build dynamic libraries for iOS and ...

    • 0 Answers
  • bash - How to check if a process id (PID) ...

    • 8057 Answers
  • database - Oracle: Changing VARCHAR2 column to CLOB

    • 1842 Answers
  • What's the difference between HEAD, working tree and index, in ...

    • 1924 Answers
  • Amazon EC2 Free tier - how many instances can I ...

    • 0 Answers

Stats

  • Questions : 43k

Subscribe

Login

Forgot Password?

Footer

Follow

© 2022 Stackoverflow Point. All Rights Reserved.

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.