问题
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