Node Express app.js giving a 404 error for GET request

限于喜欢 提交于 2021-01-29 14:59:31

问题


I have looked at similar questions and they don't seem to answer my problem. I am getting a 404 error when I send a GET request. I have my router in a separate file and then calling my requests in my app.js.

I've tried to make my issue as simple as possible for this. Here's what I have:

movie-server.js:

const express = require('express')
const movieRouter = express.Router();

movieRouter
    .route('/movies')
    .get((req, res) => {
        res.send('hello from movies')
    })
module.exports = movieRouter;

app.js:

const express = require('express')
const app = express()
const movieRouter = require('./Movies/movie-server')

app.get('/', (req, res) => {
    res.send('Hello, world!') // this GET request works when I call it in Postman
})

app.use('/movies', movieRouter) // this returns a 404 Not Found error

module.exports = app

Here is the structure of my files:

I am not sure what I am missing?


回答1:


You are giving twice the /movies route, so your server will respond to http://host:port/movies/movies

The movie-server.js should contain:

const express = require('express')
const movieRouter = express.Router();

movieRouter
    .route('/') // Do not repeat /movies here
    .get((req, res) => {
        res.send('hello from movies')
    })
module.exports = movieRouter;


来源:https://stackoverflow.com/questions/65779745/node-express-app-js-giving-a-404-error-for-get-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!