在GET请求中,`req.body`总是空的

时间:2016-12-27 20:25:34

标签: rest express get

我使用的是Express 4.13.3,而我的req.body在GET请求中始终为空。它在POST请求中填充了正确的数据。为什么是这样?我在Express文档中找不到任何对这种差异的引用。

我的快速配置:

function onError(err, req, res, next) { // eslint-disable-line no-unused-vars
  // The error id is attached to `res.sentry` to be returned
  // and optionally displayed to the user for support.
  res.statusCode = 500; // eslint-disable-line no-param-reassign
  res.end(`${res.sentry}\n`);
}

const render = require('../public/assets/SSR');

const app = express();

// sentry.io
app.use(raven.middleware.express.requestHandler(process.env.SENTRY_DSN));

const db = connectDb();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(cookieParser());

if (process.env.NODE_ENV === 'dev') {
  // Hot reloading using existing express server
  const compiler = webpack(webpackConfig);
  app.use(webpackDevMiddleware(compiler, {
    noInfo: true,
    publicPath: webpackConfig.output.publicPath,
  }));
  app.use(webpackHotMiddleware(compiler));

  app.use(logger('dev'));
}

if (process.env.NODE_ENV === 'prod') {
  app.use(helmet());
}

configPassport(app, passport, db);
configRoutes(app, passport, db);
app.use(ua.middleware(process.env.GA_TRACKING_ID, { cookieName: '_ga' }));

// sentry.io
// The error handler must be before any other error middleware
app.use(raven.middleware.express.errorHandler(process.env.SENTRY_DSN));

// Optional fallthrough error handler
app.use(onError);

app.get('*', render.default);

const port = process.env.PORT || 3000;
app.listen(port);
console.log(`Listening on port ${port}`);
console.log(`You are working in ${process.env.NODE_ENV} `);

2 个答案:

答案 0 :(得分:2)

HTTP GET请求的正文应为空。它毫无意义。虽然理论上可以在GET请求中添加请求主体,但许多客户端不会拒绝或拒绝许多服务器剥离它。

简而言之:这是故意的。如果您在GET中实际拥有请求正文,请将其删除或切换到更合适的HTTP方法。

答案 1 :(得分:1)

RFC 7231,Section 4.3.1

  

GET请求消息中的有效负载没有定义的语义;在GET请求上发送有效负载主体可能会导致某些现有实现拒绝该请求。