简体   繁体   English

我在 Heroku 上部署了一个快速应用程序,但出现 404(未找到)错误

[英]I have an express app deployed on Heroku but I have 404 (not found) error

everything works in my localhost:3000 and using a baseUrl of localhost:5000一切都在我的 localhost:3000 中工作,并使用 localhost:5000 的 baseUrl

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.我将我的 baseUrl 更改为已部署的站点( https://mongodb-newsapi.herokuapp.com ),但我收到一条错误消息,提示找不到我的站点。

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)加载资源失败:服务器响应状态为 404(未找到)POST https://mongodb-newsapi.herokuapp.com/api/login 404(未找到)

this it my fetchDataApi:这是我的 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:这是我的 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.我没有添加 mongoose.connect 因为我有我的帐户。

and this is the authCtrl:这是 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:这是 github 存储库:

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

I think you refer too many articles or videos .我认为您引用了太多文章或视频。 When I check your repo there you written 2-3 types of code which does the same task.当我在那里检查你的仓库时,你编写了 2-3 种执行相同任务的代码。 I suggest you to follwo only one resource at a time.我建议您一次只关注一种资源。 May be this will help you.可能这会对你有所帮助。 https://www.thapatechnical.com/2021/04/how-to-deploy-mern-projects-on-heroku.html https://www.thapatechnical.com/2021/04/how-to-deploy-mern-projects-on-heroku.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我在 express 中收到 404 错误?我已在视图和路由文件夹中正确创建了文件 - Why am i getting the 404 error in express?I have created the files correctly in views and routes folders 在部署在 Heroku 上的 node.js + Express 应用程序中找不到 jQuery 文件 - jQuery file is not found in node.js + Express app deployed on Heroku 当我在 heroku 中部署我的应用程序时,获取 html 时出错 - Error getting html when I deployed my app in heroku (当我有 JavaScript 运行 PHP 脚本时未找到 PHP 文件路径,但出现 ZDA88B4E490C14359B639CZ4A 错误); 该怎么办? - PHP file path not found when I have JavaScript run a PHP script with XMLHTTPREQUEST (404 error); what to do? 当我尝试访问快递路线时未找到404错误 - Not Found 404 Error when i try to access an express route 我正在尝试使用 heroku 部署一个简单的 nodejs 应用程序,它已成功部署,但在打开 url 时出错? - I am trying to deploy a simple nodejs app using heroku and its is deployed successfully but giving error on opening the url? 为什么在node.js express中的IE(不是Chrome)上出现“ 404 not found”错误? 以及如何解决? - Why do i get a “404 not found” error on IE(not Chrome) in node.js express? and how to solve? 找不到模块:在Heroku上部署时出错 - Module not found: error when deployed on Heroku 我有一个jsPDF错误 - I have a jsPDF error 我的vuejs有错误 - I have an error with vuejs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM