错误 404 未找到。通过 Axios 将我的 Nest.js 与 React 连接

问题描述 投票:0回答:1

我在后端使用 Nest.js,在前端使用 React。

我似乎在通过 Axios 执行 Post 请求时遇到问题。因此,我不断收到此 404(未找到错误)。

为什么我仍然收到此 404 错误?

// FrontEnd

import React from "react";
import axios from "axios";

const AddSched: React.FC = () => {
    const handleClick = async () => {


        try{
            const createNapTimeDto = {
                userId: 5, 
                babyId: 5, 
                date: new Date().toISOString()
            }
        
            const response = await axios.post('http://localhost:3000/naptime/create', createNapTimeDto);
            console.log("Created object", response)
        }catch(error){
            console.error("There was an error", error)
        }
    };


    return (
        <div>
            <h2>Ready to log for Baby Axel</h2>
            <button onClick={handleClick}>Nap Time</button>
            <button onClick={handleClick}>Diaper Time</button>
            <button onClick={handleClick}>Tummy Time</button>
            <button onClick={handleClick}>Bath Time</button>
        </div>
    );
};

export default AddSched;


//backend

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { NapTimeEntity } from '../naptime.entity';
import { Repository } from 'typeorm';
import { UserEntity } from 'src/user/user.entity';
import { CreateNapTimeDto } from '../dto/createNaptime.dto';
import { BabyEntity } from 'src/baby/baby.entity';
import { GetOneResponseDto } from '../dto/getOneResponse.dto';

@Injectable()
export class NapTimeService {


    constructor(
        @InjectRepository(NapTimeEntity)
        private readonly napTimeRepo: Repository<NapTimeEntity>,

        @InjectRepository(UserEntity)
        private readonly userRepo : Repository<UserEntity>,

        @InjectRepository(BabyEntity)
        private readonly babyRepo : Repository<BabyEntity>



    ){}


    async create(
        createNapTimeDto: CreateNapTimeDto
    ){

        //checks if user is existing
        const existingUser = await this.userRepo.findOneBy({id: createNapTimeDto.userId})
        if(!existingUser){
            throw new NotFoundException({
                status: "Error", 
                message: "UserID not found!"
            })
        }


        //checks if a babyId matches UserId
        const matchedBaby = await this.babyRepo.findOne({
            where: {
                id: createNapTimeDto.babyId,
                user: existingUser
            }
        })


        if(!matchedBaby){
            throw new NotFoundException({
                status: "error",
                message: "baby does not belong to the specified user"
            })
        }
        // Save to naptime entity
        const newNaptime = new NapTimeEntity;

        newNaptime.date = createNapTimeDto.date;
        newNaptime.babies = matchedBaby;
        newNaptime.user = existingUser; 
        await this.napTimeRepo.save(newNaptime)

        return{
            status: "OK",
            message: "New naptime created successfully", 
            data: {
                date: createNapTimeDto.date,
                babyId: createNapTimeDto.babyId,
                userId: createNapTimeDto.userId

            }
        }
    }

}


import { Controller, Logger, Body, Query} from '@nestjs/common';
import { NapTimeService } from '../service/naptime.service';
import { Post, Get, Patch } from '@nestjs/common';
import { CreateNapTimeDto } from '../dto/createNaptime.dto';
import { UpdateNapTimeResponse } from '../dto/updateNapTimeResponse.dto';

@Controller('naptime')
export class NapTimeController {

    private readonly logger = new Logger(NapTimeController.name);
    constructor(private readonly napTimeService: NapTimeService){}


    @Post('/create')
    async createNapTime(
    
        @Body() createNapTimeDto: CreateNapTimeDto
    ){

        try{

            return this.napTimeService.create(createNapTimeDto)

        }catch(error){
            this.logger.error(NapTimeController.name, error);
            throw error
        }
    }

}

以下是我所做的一些事情:

  • 在我的后端添加了 CORS 代码。

  • 已验证 post 请求是否在 Postman 上运行。

  • 已验证我的前端在端口 3001 运行,后端在端口 3000 运行。

javascript reactjs typescript nest
1个回答
0
投票

我对nest.js不熟悉,但从axios来看,请求过程对我来说看起来不错。也许您可以尝试使用不同的 URL(例如 google 或 https://mockapi.io/)来验证 API 请求是否正在从您的应用程序运行。如果对这些 URL 中的任何一个的请求有效(响应!=404),您应该检查您的嵌套应用程序。

© www.soinside.com 2019 - 2024. All rights reserved.