获取请求在 Node.JS 中不起作用并表达
get request not working in Node.JS and express
我的 app.get('*') 不是 运行,我不知道为什么。我也尝试过使用“/”作为路线,但我无法获得任何东西 return。我已经在下面发布了代码。
const express = require('express');
const morgan = require('morgan');
const shoeRouter = require('./routes/shoeRouter');
const app = express();
// MIDDLEWARE
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
app.use(express.json());
// ROUTES
app.use('/api/shoes', shoeRouter);
app.use((err, res) => {
return res.json({ errorMessage: err.message });
});
const path = require('path');
app.use(express.static(path.join(__dirname, '/../client/build')));
app.get('*', (req, res) => {
res.send('Hello World');
});
module.exports = app;
我认为,你应该把 app.get('*')
放在 app.use('/api/...')
之前
问题可能出在您的全局错误处理程序上。您已经注册了一个带有两个参数的中间件函数,Express 将其视为常规 (req, res) => void
中间件。它不对参数名称进行任何检查。
要注册全局错误处理中间件,您需要一个至少有 4 个参数的函数
app.use((err, req, res, next) => {
return res.json({ errorMessage: err.message });
});
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
)
我的 app.get('*') 不是 运行,我不知道为什么。我也尝试过使用“/”作为路线,但我无法获得任何东西 return。我已经在下面发布了代码。
const express = require('express');
const morgan = require('morgan');
const shoeRouter = require('./routes/shoeRouter');
const app = express();
// MIDDLEWARE
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
app.use(express.json());
// ROUTES
app.use('/api/shoes', shoeRouter);
app.use((err, res) => {
return res.json({ errorMessage: err.message });
});
const path = require('path');
app.use(express.static(path.join(__dirname, '/../client/build')));
app.get('*', (req, res) => {
res.send('Hello World');
});
module.exports = app;
我认为,你应该把 app.get('*')
放在 app.use('/api/...')
问题可能出在您的全局错误处理程序上。您已经注册了一个带有两个参数的中间件函数,Express 将其视为常规 (req, res) => void
中间件。它不对参数名称进行任何检查。
要注册全局错误处理中间件,您需要一个至少有 4 个参数的函数
app.use((err, req, res, next) => {
return res.json({ errorMessage: err.message });
});
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
)