本文介绍了Node Express app.js给出GET请求的404错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看过类似的问题,但它们似乎无法回答我的问题.发送GET请求时出现404错误.我将路由器放在单独的文件中,然后在app.js中调用我的请求.
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:
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
这是我文件的结构:
我不确定我缺少什么?
推荐答案
您给出了两次/movies
路由,因此您的服务器将响应http://host:port/movies/movies
You are giving twice the /movies
route, so your server will respond to http://host:port/movies/movies
movie-server.js
应该包含:
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;
这篇关于Node Express app.js给出GET请求的404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!