【问题标题】:can not get request body using bodyParser无法使用 bodyParser 获取请求正文
【发布时间】:2020-11-04 13:47:56
【问题描述】:

我正在构建一个 NextJS React 应用程序。 在我的 server/index.tsx 中,我得到:

import next from 'next';
import express from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import { parse } from 'url';
import { createServer as createHttpServer } from 'http';
import { ParsedUrlQuery } from 'querystring';

const port = 9000;
const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({ dev });

const handleNextRequests = nextApp.getRequestHandler();

/**
 * Compression setup
 */
const shouldCompress = (
  req: express.Request,
  res: express.Response
): boolean => {
  // don't compress responses explicitly asking not
  if (req.headers['x-no-compression']) {
    return false;
  }

  // use compression filter function
  return compression.filter(req, res);
};

nextApp.prepare().then(() => {
  /**
   * Express application setup
   */
  const expressApp = express();

  // setup compression in express
  expressApp.use(compression({ filter: shouldCompress }));
  expressApp.use(bodyParser.urlencoded({ extended: true }));
  expressApp.use(bodyParser.json());
  expressApp.use(bodyParser.raw());
  expressApp.use(express.json()); 

  ...

  expressApp.post("/api/client", async (_req: express.Request, _res: express.Response) => {
    
    console.log(_req.body)
    _res.send(_req.body)
  });


  // fallback all requests to next request handler
  expressApp.all('*', (req: express.Request, res: express.Response) => {
    return handleNextRequests(req, res);
  });

  createHttpServer(expressApp).listen(port, async (err?: any) => {
    if (err) {
      throw err;
    }
    console.log(`HTTP server listening on port: ${port}`);

  });
});

在客户端,我正在拨打这样的电话:

console.log('json: '+JSON.stringify(inputData))
    await fetch('http://localhost:9000/api/client',{
        method: 'POST',
        body: JSON.stringify(inputData)
    }).then(res => res.json());

当我尝试记录 JSON.stringify(inputData) 时,对象已正确更改为 JSON 字符串, 但是当我尝试从服务器端记录 _req.body 时,它总是 {}

请帮我弄清楚我做错了什么。

【问题讨论】:

    标签: typescript express fetch next.js body-parser


    【解决方案1】:

    尝试在标头中设置 json :

    await fetch('http://localhost:9000/api/client',{
        method: 'POST',
        body: JSON.stringify(inputData),
        headers: {
             'Content-Type': 'application/json'
        },
    

    【讨论】:

      猜你喜欢
      • 2014-12-08
      • 2015-10-15
      • 2016-08-01
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 2015-08-19
      • 1970-01-01
      相关资源
      最近更新 更多