简体   繁体   English

NodeJS + Express:服务器无法解析 GET、PUT、POST 或 DELETE 请求(状态 404)

[英]NodeJS + Express: Server cannot resolve GET, PUT, POST, or DELETE requests (Status 404)

server.js

const express = require('express')
const dotenv = require('dotenv').config()
const port = process.env.PORT ||9999
const goals = require('./routes/goalRoutes')
const app = express()

app.use('/api/goals', goals)
app.listen(port, () => console.log(`Server started on port ${port}`))

goalRoutes.js defines a route api/goals goalRoutes.js定义了一个路由api/goals

const express = require('express')
const router = express.Router()
const { createGoal, getGoals, updateGoal, deleteGoal, } = require('../controllers/goalController')

router.route('/').post(createGoal).get(getGoals)
router.route('/:id').put(updateGoal).delete(deleteGoal)

module.exports = router

goalController.js gives functionality to that route goalController.js为该路由提供功能

//@desc     Create goal
//@route    POST /api/goals
//@access Private
const createGoal = (err, req, res, next) => {
    res.status(200).json({message: "Create goal"})
}

//@desc     Get goals
//@route    GET /api/goals
//@access Private
const getGoals = (err, req, res, next) => {
    res.status(200).json({message: "Read goals"})
}

//@desc     Update goal
//@route    PUT /api/goals:id
//@access Private
const updateGoal = (err, req, res, next) => {
    res.status(200).json({message: `Update this goal: ${req.params.id}`})
}

//@desc     Get goals
//@route    DELETE /api/goal/:id
//@access Private
const deleteGoal = (err, req, res, next) => {
    res.status(200).json({message: `Delete this goal: ${req.params.id}`})
}

module.exports = {
    createGoal,
    getGoals,
    updateGoal,
    deleteGoal,
}

I have created a route (intended as /api/goals ) and controllers for that route.我已经为该路由创建了一个路由(意图为/api/goals )和控制器。 I then used the controllers found in goalController.js to handle GET, PUT, POST, and DELETE requests and connected that to goalRoutes.js .然后,我使用在goalController.js中找到的控制器来处理 GET、PUT、POST 和 DELETE 请求,并将其连接到goalRoutes.js

Using Postman for testing, I can only resolve these requests with a 404 status.使用 Postman 进行测试,我只能以 404 状态解析这些请求。

My initial thought process was that I didn't correctly import the controller functions into goalRoutes.js , but I seem to have exported them as an object just fine and Node doesn't seem to have an issue with anything at runtime.我最初的想法是我没有正确地将控制器函数导入到goalRoutes.js中,但我似乎已经将它们导出为对象就好了,而且 Node 在运行时似乎没有任何问题。

I used to have the body of the controllers' functions within the callback functions of router.get , router.post , router.put , and router.delete but that was really messy.我曾经在router.getrouter.postrouter.putrouter.delete的回调函数中拥有控制器函数的主体,但这真的很混乱。 I would strongly prefer not to go back to that mess.我强烈希望不要回到那个烂摊子。

I am at a loss.我很茫然。 What's stopping the callback functions of router.route to use the controller functions?是什么阻止router.route的回调函数使用控制器函数? Why does Postman receive 404?为什么邮递员会收到 404?

I apologize if my terminology sucks.如果我的术语很糟糕,我深表歉意。 I'm a total beginner at Javascript.我是 Javascript 的初学者。

You've registered all your controllers as error handling middleware .您已将所有控制器注册为错误处理中间件

Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: (err, req, res, next)以与其他中间件函数相同的方式定义错误处理中间件函数,除了错误处理函数有四个参数而不是三个: (err, req, res, next)

Remove the first err parameters from each of them从每个参数中删除第一个err参数

const createGoal = (req, res, next) => {
  res.json({message: "Create goal"})
}

const getGoals = (req, res, next) => {
  res.json({message: "Read goals"})
}

const updateGoal = (req, res, next) => {
  res.json({message: `Update this goal: ${req.params.id}`})
}

const deleteGoal = (req, res, next) => {
  res.json({message: `Delete this goal: ${req.params.id}`})
}

FYI, the default response status when using res.json() is 200.仅供参考,使用res.json()时的默认响应状态为 200。

You have to try this one in goalRoutes.js file你必须在goalRoutes.js 文件中尝试这个

router.use('/').post(createGoal).get(getGoals)
router.use('/:id').put(updateGoal).delete(deleteGoal)

if you use nodejs module import try implementing this into your code, it works如果您使用 nodejs 模块导入,请尝试将其实现到您的代码中,它可以工作

export default ()=> {
    const app = Router()

    RolesRoute(app)
    auth(app)
    FlightRoute(app)
    MaintenanceRoute(app)
    Books(app)

    app.use('/user',UserRoute())

    app.use('/engineer', EngineerRoute())
    app.use('/instructor', InstructorRoute())

    return app
}

Auth Routes认证路由



import { Router } from 'express'

import {AuthValidator} from "../../../lib/validator";
import AuthController from "../../../controllers/auth.controller";
import {isAdmin, isAuth} from "../../../lib/middleware/auth";

const route = Router();
export default (app)=> {
    app.use('/auth', route);

    /**
     * Sign in
     */
    route.post("/signIn", AuthValidator.signInValidator, AuthController.signIn)

}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM