gpt4 book ai didi

typescript - 无法使用 bodyParser 获取请求正文

转载 作者:行者123 更新时间:2023-12-04 12:37:35 25 4
gpt4 key购买 nike

我正在构建一个 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 时,它总是 {}
请帮我弄清楚我做错了什么。

最佳答案

尝试在 headers 中设置 json :

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

关于typescript - 无法使用 bodyParser 获取请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62908484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com