Uber API - HTTP Response with error code: 409 - node.js

I'm using the Uber API to create a ride request (with node-uber)
I first get the user authenticated (uber.authorization after getting a calback from uber.getAuthorizeUrl).
Then I call the estimate API and get a response (estimates.getPriceForRoute)
I then use the same start & end coordinates with the product ID returned in the estimate (requests.create).
I always get back: HTTP Response with error code: 409
Any suggestions?
UPDATE
Here is the code for the estimate request (which works perfectly)
router.get('/estimate', function(request, response, next) {
var query = url.parse(request.url, true).query;
if (!query || !query.start_lat || !query.start_lng || !query.end_lat || !query.end_lng) {
response.sendStatus(400);
} else {
uber.estimates.getPriceForRoute(query.start_lat, query.start_lng, query.end_lat, query.end_lng , 1, function(err, res){
if (err) {
console.error(err);
response.sendStatus(500);
} else {
var productType = getProductType(query);
var selectedProduct = _.find(res.prices, function(price){
return price.display_name == productType;
});
response.json(selectedProduct);
}
});
}
});
Here is the response I get
{"localized_display_name":"uberX","high_estimate":7,"minimum":7,"duration":240,"estimate":"$7-7","distance":0.95,"display_name":"uberX","product_id":"a1111c8c-c720-46c3-8534-2fcdd730040d","low_estimate":7,"surge_multiplier":1,"currency_code":"USD"}
Now the part that has the problem:
router.get('/request', function(request, response, next) {
var query = url.parse(request.url, true).query;
if (!query || !query.start_lat || !query.start_lng || !query.end_lat || !query.end_lng || !query.productId) {
response.sendStatus(400);
} else {
uber.requests.create({
"product_id": query.productId,
"start_latitude": query.start_lat,
"start_longitude": query.start_lng,
"end_latitude": query.end_lat,
"end_longitude": query.end_lng
}, function (err, res) {
if (err) {
console.error("error: " + err);
response.sendStatus(400);
} else {
//console.log(res);
response.json(res);
}
});
}
});
the line console.error("error: " + err); returns this output:
error: HTTP Response with error code: 409

Could you please share your source code? I assume you try to call /v1/requests/estimate endpoint. This endpoints can return a 409 - Conflict. This status indicates that there is a surge in place right now. Here is a description of the surge flow:
The node-uber project does not actively support with handling a surge in the released version. However, there is a branch for v1.0.0 and someone started working on a direct support, as listed in this issue conversation.

Related

softlayer-client: unable to update VPN for User_Customer via REST API

I am experimenting with the softlayer-client api wrapper in my Node Express application. My goal is to update the VPN password of a User_Customer by calling the updateVpnPassword method on a specific user.
I can construct a call to achieve a VPN password update using request, but I'm not sure it's the best way to achieve the desired result.
Can the softlayer-client module be used to make an similar call to this:
function updateVpnPassword(req, res, next) {
// Construct URL to update VPN
myURL = 'https://' + <userIDAdmin> + ':' + <apiKeyAdmin> + '#api.softlayer.com/rest/v3/SoftLayer_User_Customer/' + <softLayerID> + '/updateVpnPassword/' + <newPassword> + '.json';
request.get({url: myURL}, function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
});
next();
}
My initial attempts have been to try variations on this:
function updateVpnPassword(req, res, next) {
// Assuming var client = new SoftLayer();
client
.auth(<userIDAdmin>, <apiKeyAdmin>)
.path('User_Customer', <softLayerID>,'updateVpnPassword')
.parameters(<newPassword>)
.put(function(err,result){
console.log(result);
if (err) {
next(err); // Pass errors to Express.
}
else {
// update successful
}
});
next();
}
But the console log gives an error response like
{ message: { error: 'Internal Error', code: 'SoftLayer_Exception_Public' } }.
I expect a TRUE or FALSE response, to indicate the whether the update is successful.
A similar python client can be found here but I require an implementation in JS.
I'm not familiar with nodejs but I installed the package softlayer-node and run your second code and it worked.
I also created the following script and I got TRUE
var username = 'set me';
var apikey = 'set me';
var userId = 1111111;
var SoftLayer = require('softlayer-node');
var client = new SoftLayer();
client
.auth(username, apikey)
.path('User_Custome', userId, 'updateVpnPassword')
.parameters('P#ssword123')
.put()
.then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
node command:
$ node updateVpnPassword.js
true
Did you tried by sending that request using curl or any other REST client like postman?
If you get the same error then I recommend you submit a ticket and provide information like the id of users you are trying to update the vpn password and the user with which you are sending the request.

Bad Request error in uber api

I've been trying to get the uber price estimates endpoint working, but I'm stuck on an error that leads me to a blank page saying, "Bad Request." The console also says "callback not a function" but I can't seem to find out what is wrong.
My route:
// Get an upfront fare before requesting a ride
app.get('/v1.2/estimates/price', function(request, response) {
// extract the query from the request URL
var query = request.query;
// if no query params sent, respond with Bad Request
if (!query || !query.lat || !query.lng) {
response.sendStatus(400);
} else {
uber.estimates.getPriceForRouteAsync( {
"product_id": "33de8094-3dc4-4ca9-8f67-243275f57623",
"start_latitude": "38.9597897",
"start_longitude": "-94.60699369999999",
"end_latitude": "39.010969",
"end_longitude": "-94.61509899999999"
})
.then(function(res) {
log(res);
})
.error(function(err) {
console.error(err);
});
}
});
Any help is appreciated.
Please check out the README for node-uber. The method does not take a JSON object but the arguments in the method call:
uber.estimates.getPriceForRouteAsync(38.9597897, -94.606994, 39.010969, -94.615098)
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
Also, the product ID is not needed as the /estimates/price endpoint returns an array of estimates for each product.

POST request 404 (Not Found) - express-http-proxy

I'm trying to send a POST request to my api but it gives me following error:
I'm using express-http-proxy package for node to send request. Here is my code:
app.use('/api', proxy(targetUrl, {
forwardPath: (req, res) => {
return require('url').parse(req.url).path;
}
}));
In my ReactJs application, I'm using superagent to pass my request and here is request creation code:
methods.forEach((method) =>
this[method] = (path, data = {}, params = {}) => new Promise((resolve, reject) => {
const request = superagent[method](formatUrl(path));
request.set('Token', 'cb460084804cd40');
if (params) {
request.query(params);
}
if (__SERVER__ && req.get('cookie')) {
request.set('cookie', req.get('cookie'));
}
if (data) {
request.send(data);
}
console.log('sending: ', request);
// request.end((err, { text } = {}) => {console.log('ended: ', text, err);});
// reject();
request.end((err, { text } = {}) => err ? reject(text || err) : resolve(text));
}));
formatURL Function
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
if (__SERVER__) {
return 'https://' + config.apiHost + adjustedPath;
}
return '/api' + adjustedPath;
}
In addition to this, when I send GET request, it gives me following error:
Also, when I try to send POST request on my live APIserver it gives 404 Not Found error but if I try to send POST request on my localhost APIServer it gives 504 Gateway_Timeout error.
I am not confident about this behaviour. Therefore, need your help to find the problem. Thanks for your time in advance.

AZURE Mobile Service forwarding POST request in insert script of table

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?
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.
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");
}
});
}

node.js' express middleware does not return error on nodester

My node app uses the express framework. I developed a middleware to check parameters but when an error is sent by the middleware it is not sent back in the response.
I only have this problem on nodester, on localhost it works as expected.
Here is an example of the controller action:
/*
* Create a new user
*
*/
app.post('/user/create', md.checkParams(["nickname", "email", "password"]), function(req, res){
var email = req.query.email;
var nickname = req.query.nickname;
var password = req.query.password;
jsonObj = { "nickname" : nickname, "email" : email, "password" : password };
// Save user in DB
db.hmset("user:" +nickname, jsonObj, function(err1){
if(!err1) {
db.sadd("users","user:" + nickname, function(err2){
if(err2){
jsonObj = {"error" : "database error", "message" : "error adding object to set" };
}
h.respond(res, jsonObj);
});
} else {
jsonObj = {"error" : "database error", "message" : "error creating hash for object" };
h.respond(res, jsonObj);
}
});
});
The checkParams middleware is:
function checkParams(arr){
return function(req, res, next) {
// Make sure each param listed in arr is present in req.query
var missing_params = [];
for(var i=0;i<arr.length;i++){
if(! eval("req.query." + arr[i])){
missing_params.push(arr[i]);
}
}
if(missing_params.length == 0){
next();
} else {
next(JSON.stringify({ "error" : "query error", "message" : "Parameter(s) missing: " + missing_params.join(",") }));
}
}
}
For instance, if I use a
curl -XPOST 'http://HOST/users/create'
on localhost I get:
{"error":"query error","message":"Parameter(s) missing: nickname,email,password"}
on NODESTER I only got:
Internal Server Error
({"error":"query error","message":"Parameter(s) missing: nickname,email,password"} appears in the app log but not in the response)
Any idea what could be wrong ?
UPDATE
I found a workaround by issuing the following in the middleware when an error is supposed to be thrown:
res.writeHead(200, {'content-type': 'application/json'});
res.write("my error message");
res.end();
instead of
next("my error message);
it's working this way even if I'm not 100% sure this is best solution.
Look at your express configuration settings.
by default under "development" the server returns error details whereas under "deployment" it hides them.
Update
With regards to your proposed solution. I would recommend you call next with multiple non standard parameters i.e.
next("error", data)
And then have a global middleware in connect that acts as a global error handling mechanism where you write error data to the response in your own personal manner.
You may have some edge cases where the middlewares behave strangely. You'll have to look into how next works in detail.

Resources