aws lambda调用不在POST上填充正文 [英] aws lambda call not populating body on POST

查看:161
本文介绍了aws lambda调用不在POST上填充正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢EVK对我以前的Q的帮助(可以使用API获取但不是API POST )当我可以点击GET时,我能够解决无法从节点中的aws lambda发出API POST请求的问题。问题不在于填充post_options。

Thanks to help from EVK on my previous Q (can use API GET but not API POST) I was able to resolve the problem of not being able to make an API POST request from an aws lambda in node, when I could hit the GET. The problem was not populating post_options.

无论如何,现在我能够成功调用帖子,但我无法填充正文。

Anyway, now I am able to successfully call the post but I cant get the body populated.

相关文档 https://nodejs.org/api/http.html# http_http_request_options_callback

如果您在下面看到我的API POST调用。

If you see my API POST call below.

 //// POST api/<controller>
      public string SapEaiCall([FromBody]string xmlFile)
        {
            string responseMsg = "Failed Import Active Directory User";

            if (string.IsNullOrEmpty(xmlFile))
            {
                responseMsg = "XML file is NULL";
            }

            if (responseMsg != "XML file is NULL")
            {
                xmlFile = RemoveFirstAndLastQuotes(xmlFile);

                if (!IsNewestVersionOfXMLFile(xmlFile))
                {
                    responseMsg = "Not latest version of file, update not performed";
                }
                else
                {
                    Business.PersonnelReplicate personnelReplicate = BusinessLogic.SynchronisePersonnel.BuildFromDataContractXml<Business.PersonnelReplicate>(xmlFile);
                    bool result = Service.Personnel.SynchroniseCache(personnelReplicate);

                    if (result)
                    {
                        responseMsg = "Success Import Sap Cache User";
                    }
                }
            }

            return "{\"response\" : \" " + responseMsg + " \" , \"isNewActiveDirectoryUser\" : \" false \"}";

        }

每当我从aws lambda调用它时,它返回 responseMsg =XML文件为空;

Every time I call it from the aws lambda, it returns responseMsg = "XML file is NULL";

请参阅下面的示例:

    var querystring = require('querystring');
var https = require('https');
var fs = require('fs');

exports.handler = function(event, context) {

   const post_data = querystring.stringify({'msg': 'Hello World!'});

    // An object of options to indicate where to post to
    var post_options = {
        host: 'URL',
        protocol: 'https:',
        port: '443',
        path: '/api/SyncPersonnelViaAwsApi/SapEaiCall',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': post_data.length
        }
    };

    //ignores SSL
   process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    var post_request = https.request(post_options, function(res) {
        var body = "";

        res.on('data', function(chunk)  {
            body += chunk;
        });

        res.on('end', function() {
            context.done(body);
        });

        res.on('error', function(e) {
            context.fail('error:' + e.message);
        });
    });

    // post the data
    post_request.write(post_data);
    post_request.end();
 console.log("posted data " +post_data); //returns posted data msg=Hello%20World!
};

所以我填充了帖子数据,并尝试填充正文。仍然返回 XML文件为NULL

So I have populated post data, and also tried populating the body. Still returns XML file is NULL

有没有人知道为什么?

谢谢

推荐答案

您正在发送正文中的以下文字:

You are sending the following text in body:

msg=Hello%20World!

并说明请求内容类型为:

And you state that request content type is:

'Content-Type': 'application/json'



<你的身体代表有效的json吗?它没有。所以这是第一个问题 - 您的请求中说明的内容类型和您的发送的实际数据彼此不匹配。

Does your body represents valid json? It doesn't. So that's first problem - content type stated in your request and actual data your send do not match each other.

然后让我们看看:

public string SapEaiCall([FromBody]string xmlFile)

它基本上说:查看请求的主体并使用适合请求内容类型的绑定器来绑定 xmlFile 参数的值。由于请求内容类型是application / json - binder期望body包含一个单独的json字符串,也就是说,在这种情况下,body应该是(包括引号):

It basically says: look at the body of request and use binder appropriate for request content type to bind value of xmlFile parameter. Since request content type is "application/json" - binder expects body to contain one single json string, that is, body in such case should be (including quotes):

"Hello World!"

所以如果你传递了它(例如通过 const post_data = JSON.stringify ('Hello World!'); - 它应该可以工作。

So if you pass that (for example via const post_data = JSON.stringify('Hello World!'); - it should work.

但是如果你想在体内传递更多参数怎么办?只需 xmlFile ?然后你需要定义一个模型,我会说即使你只有一个参数 - 最好这样做。例如:

But then what if you want to pass more parameters in your body, not just xmlFile? Then you need to define a model, and I'd say even if you have just one parameter - it's better to do that. For example:

public class SapEaiCallParameters {
    public string XmlFile { get; set; }
}

// FromBody can be omitted in this case
public IHttpActionResult Post(SapEaiCallParameters parameters) {

}

然后你按照预期调用它,传递json:

And then you call it as you would expect, passing json:

const model = {xmlFile: 'Hello World!'};
const post_data = JSON.stringify(model);

旁注:不要这样做:

return "{\"response\" : \" " + responseMsg + " \" , \"isNewActiveDirectoryUser\" : \" false \"}";

相反,创建另一个模型,如下所示:

Instead, create another model, like this:

public class SapEaiCallResponse {
    public string Response { get; set; }
    public bool IsNewActiveDirectoryUser { get; set; }
}

并将其退回:

    public IHttpActionResult Post(SapEaiCallParameters parameters) {
        ...
        return Json(new SapEaiCallResponse {
            Response = responseMsg,
            IsNewActiveDirectoryUser = false,
        });
    }

这篇关于aws lambda调用不在POST上填充正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆