Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

javascript - 如何在Moleculer中获取请求正文(How do I get request body in Moleculer)

According to the API documentation, to receive json as formData from a POST request, one must use body-parser.

(根据API文档,要从POST请求接收json作为formData,必须使用body-parser。)

I have declared it in the gateway service but I can still not receive the formData in my action.

(我已经在网关服务中声明了它,但是我仍然无法在操作中收到formData。)

api.service.js

(api.service.js)

module.exports = {
 name: "api",
 mixins: [ApiGateway],

 settings: {
    port: process.env.PORT || 3000,

    routes: [{
        path: "/api",
        aliases: {
          "POST users": "users.insertUser",
        },
        //The API Documentation recomends using the body-parser here
        bodyParsers: {
            json: true,
            urlencoded: { extended: true }
        },
    }],

    // In some example they also set the body-parser here
    bodyParsers: {
        json: true,
        urlencoded: { extended: true }
    },
 },
};

In the actions service.insertUser action I am supposed to receive the req.body as ctx.params, however it is always empty

(在操作service.insertUser操作中,我应该以ctx.params的形式接收req.body,但是它始终为空)

My users.service.js

(我的users.service.js)

    actions: {
    insertUser: {
        handler(ctx) {
            this.logger.info("posting", ctx.params); // -> prints {} instead of the formData
        }
    }
  ask by fabrigeas translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

have you tried giving params

(你试过给参数)

insertUser: {
            auth: "required",
            params: {
                function_id: { type: "string" },
                role_id: { type: "string" },
            },
            handler(ctx) { ctx.params.role_id 

img


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...