【问题标题】:POST request freezes after add body-parser添加正文解析器后 POST 请求冻结
【发布时间】:2020-08-20 03:52:38
【问题描述】:

我正在构建 vue 应用,我的应用需要从客户端向服务器发出 api 请求,还需要代理任何请求。

这是我的 vue.config.js

const producer = require('./src/kafka/producer');
const bodyParser = require('body-parser')

module.exports = {
    devServer: {
        setup: function (app, server) {
            app.use(bodyParser.json())
            app.post('/send-message', function (req, res) {
                producer.send(req.body)
                    .then(() => {
                        res.json({result: true, error: null});
                    })
                    .catch((e) => {
                        res.status(500).json({result: false, error: e});
                    })
            });
        },
        proxy: {
            '/v2/order/by-number': {
                target: 'http://address-here'
            }
        }
    }
};

如你所见,我正在使用 body-parser app.use(bodyParser.json())

添加后,代理不再为我工作。显示错误后对 /send-message 的请求冻结

代理错误:无法从 localhost:8080 代理请求 path-here 到 http://address-here

互联网搜索没有找到解决方案。

【问题讨论】:

  • 如果您调用 app.use(bodyParser.json()) 那么为什么要将 bodyParser.json() 作为中间件添加到 '/send-message' 路由?
  • 抱歉,忘记删除了。
  • 那么如果你在 producer.send(req.body) 行设置断点就永远不会触发?
  • 没错。它永远不会触发
  • 您有多大的请求?默认情况下 bodyParser.json() 最多允许 100KB

标签: vue.js webpack-dev-server


【解决方案1】:

找了很久,解决办法: 将第二个参数jsonParser 添加到 app.post()

查看完整示例

const producer = require('./src/kafka/producer');
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json({limit: '1mb'});

module.exports = {
        devServer: {
            setup: function (app, server) {
                app.post('/send-message', jsonParser, function (req, res) {
                    producer.send(req.body)
                        .then(() => {
                            res.json({result: true, error: null});
                        })
                        .catch((e) => {
                            res.status(500).json({result: false, error: e});
                        })
                });
            },
            proxy: {
                'path': {
                    target: 'http://address-here'
                }
            }
        }
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2019-05-11
    • 2021-06-28
    相关资源
    最近更新 更多