AZURE Mobile Service forwarding POST request in in

2019-08-08 20:59发布

I'm trying to use Azure Mobile Service to process / handle GET and POST requests on an empty data table. (really just using the mobile service as a pass through) As part of this I'm trying to forward the request to another url and receive the response back and return it via mobile service. I've figured out the GET part shown below but I'm having trouble the POST part.

GET Part:(Which works)

    function read(query, user, request)
{
   var p = request.parameters;
   var httpRequest = require('request');    
   var url = 'http://someURL/'+ p.ssoid;

    httpRequest.get(url, function(err, response, body) 
    {
        if (err)
        {
            request.respond(500, "INTERNAL SERVER ERROR"); 
        }
        else
         {
            request.respond(200,JSON.parse(body) ); 
        }

    });

}

Post Code:(Does not work)

function insert(item, user, request) 
{
   var p = request.parameters;


require('request').post({
    uri:'http://someURL/',
    headers:{'content-type': 'application/json'},
   body:p.body
    },function(err,res,body){
              if (err)
        {
            request.respond(500, "INTERNAL SERVER ERROR"); 
        }
        else
         {
            request.respond(200,"Success"); 
        }
});

}

I know the POST requires a body with the post information, but how to I get it to pass forward?

2条回答
Summer. ? 凉城
2楼-- · 2019-08-08 21:15

On an insert, the body of the request will be stored in the item argument (assuming you're passing a JSON object). So your function would look something like this:

function insert(item, user, request) 
{
    var p = request.parameters;
    require('request').post({
        uri : 'http://someURL/',
        headers : {'Content-Type': 'application/json'},
        body : item
    }, function(err, res, body){
        if (err)
        {
            request.respond(500, "INTERNAL SERVER ERROR"); 
        }
        else
        {
            request.respond(200,"Success"); 
        }
    });
}

On a related note, if you're using the mobile service as a simple pass-through, you can also consider using a custom API instead of a table, where you can also apply your logic without having any (empty) table behind it.

查看更多
Anthone
3楼-- · 2019-08-08 21:28
function insert(item, user, request) 
{
    var p = request.parameters;
    require('request').post({
        uri : 'http://someURL/',
        headers : {'Content-Type': 'application/json'},
        body : JSON.stringify(item)
    }, function(err, res, body){
        if (err)
        {
            request.respond(500, "INTERNAL SERVER ERROR"); 
        }
        else
        {
            request.respond(200,"Success"); 
        }
    });
}
查看更多
登录 后发表回答