Azure function app returning 502 Bad Gateway - azure

I am getting the error message below when I run a HTTP Triggered function app on our main slot :
Status: 502 Bad Gateway
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>502 - Web server received an invalid response while acting as a gateway or proxy server.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;}
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;}
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;}
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
<div class="content-container"><fieldset>
<h2>502 - Web server received an invalid response while acting as a gateway or proxy server.</h2>
<h3>There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.</h3>
</fieldset></div>
</div>
</body>
</html>
But when I tried to create a new slot and function app with the same exact code, it works fine without getting the error above. It seems like there's an issue with our main slot's configuration but I just can't find any resource to point me to it.
Has anyone else encountered this problem? How did you fix it?

I have this problem when I sent object from MongoDB (by Mongoose method: Model.find()) directly to the response.
Claim.find()
.then(claims => {
context.res = {
status: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: claims
};
context.done();
})
I must change this body object to:
Claim.find()
.then(claims => {
context.res = {
status: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.parse(JSON.stringify(claims))
};
context.done();
})

I have seen 502 error many times in different situations.
Most times it is my programming mistake/ config issue.
But today it took a lot more time to find this issue, so sharing here.
Issue #1
s3 = new AWS.S3();
AWS.config.loadFromPath(dirName1 + '\\aws-config.json');
s3.listObjectsV2(..);
Here, though the error is at line 1, the issue happens at line 3
Solution is:
AWS.config.loadFromPath(dirName1 + '\\aws-config.json');
s3 = new AWS.S3();
s3.listObjectsV2(..);
That is, after loading the aws config, we need to create s3 new instance variable.
Issue #2
As given here, https://stackoverflow.com/a/39240447/984471, is about writing file to un-accessible directory, while you can write to D:\local\Temp, we can't write other directories like current directory or D:\
Unfortunately, in the above examples and also other instances I had, the Azure function exists without any log in azure function console, so there is need for a lot debugging required.

I was also getting the same error. I wrote " context.done(null,output)" at the end of event handler function and it is working fine.

In my case it was a missing WEBSITE_NODE_DEFAULT_VERSION application setting (Node.js Windows function app, error occurs in both Premium and Consumption hosting plans).

The app setting is set automatically if you create a function app in Azure Portal, but you need to set it explicitly if you use an IaC tool (Terraform in my case).
"WEBSITE_NODE_DEFAULT_VERSION" = "~14"

I had the same error and i simply forgot to add the "Content-Type" Header "application/json". After adding the header it works fine for me

If you get 502:s and even lack application insights log entries...
Sanity check:
Have you deployed your application?

Related

NodeJs HTTP Request Not working with proxy (407)

I've been using the NPM Request package for years now and despite the fact that it's deprecated, it has always worked perfectly for my needs and I haven't ever had any issues up until today...
I am trying to do a regular GET request with a user:pass authenticated proxy and some additional headers - the same thing I've done a thousand times in the past, however this time the url is HTTP instead of HTTPS.
For whatever reason because the link is HTTP it is messing with my proxy authentication and for whatever reason is returning a response code of 407 and the response body shows an error stating Cache Access Denied (ERR_CACHE_ACCESS_DENIED). This is where I'm confused as to what to do because I know for a fact that there shouldn't be anything wrong with my proxy authentication since its the same thing I've done for years and years.
Request Code:
const request = require('request').defaults({
timeout: 30000,
gzip: true,
forever: true
});
cookieJar = request.jar();
proxyUrl = "http://proxyUsername:proxyPassword#proxyDomain:proxyPort";
request({
method: "GET",
url: "http://mylink.com",
proxy: proxyUrl,
jar: cookieJar,
headers: {
"Proxy-Authorization": new Buffer('proxyUsername:proxyPassword').toString('base64'),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
},
followAllRedirects: true
}, (err, resp, body) => {
if (err || resp.statusCode != 200) {
if (err) {
console.log(err);
} else {
console.log(resp.statusCode);
console.log(resp.body);
}
return;
}
console.log(resp.body);
});
Snippet of Response Body (Status Code 407):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta type="copyright" content="Copyright (C) 1996-2019 The Squid Software Foundation and contributors">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ERROR: Cache Access Denied</title>
<style type="text/css"><!--
body
:lang(fa) { direction: rtl; font-size: 100%; font-family: Tahoma, Roya, sans-serif; float: right; }
:lang(he) { direction: rtl; }
--></style>
</head><body id=ERR_CACHE_ACCESS_DENIED>
<div id="titles">
<h1>ERROR</h1>
<h2>Cache Access Denied.</h2>
</div>
<hr>
...
<p>Sorry, you are not currently allowed to request http://mylink.com from this cache until you have authenticated yourself.</p>
...
Other things to note:
I have also connected to the exact same proxy on my browser and gone to the same site and it works perfectly so it's not an issue with the proxy itself.
If I remove the proxy from the request it works perfectly, so maybe I have configured the request wrong for HTTP is all I can think of
Now as I said this exact code works flawlessly with any HTTPS link so that's where I'm stumped. Any help would be appreciated!
Changed the Proxy-Authorization header to Proxy-Authenticate and that seemed to work perfectly. I have no clue why it requires that for HTTP but there you go, not much documentation on the matter...

Calling databricks notebook using Databricks Job api runs-submit endpoint

I am trying to establish an AWS lambda function which calls a databricks notebook (in the event of an s3 trigger).I understand I have to use the Jobs API of databricks in my lambda function(python) code to make a POST request using the JSON payload of the runs-submit function.
Although the documentation is not very clear, I was able to call a test script and on checking the response text I see the databricks login page html code which means it is not getting authenticated .
I did read on user tokens but I am not sure how to even incorporate them for authentication.
Any help of making this work in other ways or helping me use the user_tokens to get authenticated so that the flow reaches the execution of the notebook rather than getting stopped at authentication page would be helpful.
Thanks in advance.
Code Sample:
import requests
import json
job_payload = {
"run_name": 'just_a_run',
"existing_cluster_id": '****',
"notebook_task":
{
"notebook_path": 'https://databricks.cloud.company.com/****'
}
}
resp = requests.post('https://databricks.cloud.company.com/2.0/jobs/runs/submit', json=job_payload)
print(resp.status_code)
print(resp.text)
200
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="Content-Language" content="en"/>
<title>Databricks - Sign In</title>
<meta name="viewport" content="width=960">
<link rel="stylesheet" href="/login/bootstrap.min.css">
<link rel="icon" type="image/png" href="login/favicon.ico" />
<meta http-equiv="content-type" content="text/html; charset=UTF8">
<link rel="shortcut icon" href="favicon.ico"><link href="login/login.e555bb48.css" rel="stylesheet"></head>
<body>
<div id="login-page"></div>
<script type="text/javascript" src="login/login.dabd48fd.js"></script></body>
</html>
SOLVED:
1) You will need to create a user token for authorization and send it as 'headers' parameter while performing the REST request.
2) headers={'Authorization': 'Bearer token'}
In place of token must be your actual token that you get from databricks.
3) The api link must start with /api
4) Path to the databricks notebook must be absolute path
i.e. "/Users/$USER_NAME/book_name"
Final Working Code:
import requests
import json
job_payload = {
"run_name": 'just_a_run',
"existing_cluster_id": 'id_of_cluster',
"notebook_task":
{
"notebook_path": '/Users/username/notebook_name'
}
}
resp = requests.post('https://databricks.cloud.company.com/api/2.0/jobs/runs/submit', json=job_payload, headers={'Authorization': 'Bearer token'})
print(resp.status_code)
print(resp.text)

amazon pay error client_Id undefined

I am integrating the amazon pay API in my asp.net code. I have write the following code
<!-- language: lang-js -->
<script type='text/javascript'>
window.onAmazonLoginReady = function () {
amazon.Login.setClientId('<%=ConfigurationManager.AppSettings["lwa_client_id"]%>');
amazon.Login.setUseCookie(true);
};
</script>
<script async type='text/javascript' src='https://static-na.payments-amazon.com/OffAmazonPayments/us/sandbox/js/Widgets.js'></script>
<script type='text/javascript'>
OffAmazonPayments.Button("AmazonPayButton", '<%=ConfigurationManager.AppSettings["merchant_id"]%>', {
type: "PwA",
authorization: function () {
debugger;
loginOptions = { scope: "profile postal_code payments:widget payments:shipping_address", popup: true };
amazon.Login.authorize(loginOptions, "/AmazonProcessing");
},
onError: function (error) {
// something bad happened
}
});
</script>
It render the Amazon Pay button. But when I click on it, It will show the popup with error of 404.
It was working before. I do not change any setting on the Amazon. I have checked the JavaScript Cross origin. I have added the localhost with port.
How to resolve this issue?
The value for client ID is probably not populated correctly from your application settings (error "Unknown client_id" and in the error summary "client_id=undefined").
You should be able to set a breakpoint in the JavaScript on the line with "setClientId" to verify whether the client ID has a value or not.

Strange pjax behavior: GET request initiates after a pjax request

The problem is, as soon as pjaxed request finishes, pjax also initiates a normal GET request.
My codes are like this:
$(document).on('pjax:end', function(event){
alert("end");
inpjax = false;
});
$(document).on('pjax:timeout', function(event) {
alert("timeout")
event.preventDefault();
});
$(document).on('pjax:error', function() {
alert("error");
});
$(document).on('pjax:success', function() {
alert("success");
});
$(document).ready(function(e) {
inpjax = false;
$('.pj').click( function(e) {
e.preventDefault();
if(!inpjax)
{
inpjax = true;
$.pjax({
timeout: 5000,
url: $(this).attr('href'),
container: '#codeport'
});
}
});
});
As you can see, it should give me an alert on different stiuations, but I only get alert on pjax:end event, and after that alert, pjax initiates normal GET request, timing is like this:
[17:36:02.002] GET http://localhost/abstract?_pjax=%23codeport [HTTP/1.1 200 OK 86 ms]
[17:36:02.170] GET http://localhost/abstract [HTTP/1.1 200 OK 73 ms]
I don't get timeout, error or success alert.
What could be causing this? Please help...
SOLUTION:
The problem turned out to be that my serverside code was responding with a full page, and that was causing a second GET request. So if this problem happens to you too, make sure that your server side code responds correctly to PJAX requests.
example:
<!DOCTYPE html>
<html>
<head>
<!-- styles, scripts, etc -->
</head>
<body>
<h1>My Site</h1>
<div class="container" id="pjax-container">
Download content from the other site ?.
</div>
</body>
</html>
Try to add pjax to an element which you want to get event messages from like $(document).pjax('a', '#pjax-container')

Another Cross-XHR related

I know that there's a bunch of questions about the "not allowed by Access-Control-Allow-Origin." error.
But I've tried some of them without success. :(
Some appointments:
I'm trying to build a dev-tools-tab extension
I can touch flickr API like the example shows
I can't reach localhost
Already tried several permission wildcards
http://localhost/
http://*/
*://*/
Already tried pack'd and unpack'd extensions
currently, manifest.json has
"version": "0.0.1",
"manifest_version": 2,
"devtools_page": "components/devtools.html",
"permissions": [
"http://*/"
]
devtools.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="../js/devtools.js"></script>
</body>
</html>
and, devtools.js
(function (window) {
"use strict";
var xhr1, xhr2, url;
xhr1 = new window.XMLHttpRequest();
xhr2 = new window.XMLHttpRequest();
xhr1.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('flickr ok');
}
};
xhr2.onreadystatechange = function () {
console.log(this.readyState);
if (this.readyState === 4) {
console.log(this.responseText);
}
};
url = 'https://secure.flickr.com/services/rest/?' +
'method=flickr.photos.search&' +
'api_key=90485e931f687a9b9c2a66bf58a3861a&' +
'text=' + encodeURIComponent('cats') + '&' +
'safe_search=1&' +
'content_type=1&' +
'sort=interestingness-desc&' +
'per_page=20';
xhr1.open('get', url, true);
xhr1.send();
url = 'http://apache.local';
xhr2.open('get', url, true);
xhr2.setRequestHeader('Origin', url);
xhr2.send();
Chrome console output:
1 devtools.js:12
Refused to set unsafe header "Origin" devtools.html:1
XMLHttpRequest cannot load http://apache.local/. Origin chrome-extension://nafbpegjhkifjgmlkjpaaglhdpjchlhk is not allowed by Access-Control-Allow-Origin. devtools.html:1
4 devtools.js:12
flickr ok devtools.js:8
Chrome version:
28.0.1500.20 dev
Thanks in any advice.
I've got it!
Actually, the problem is that I'm trying to perform XHR requests on devtools page and it seems to have no permissions to bypass cross-origin-access policies like a popup page do.
Devtools tab tries are also unsuccessful.
edit
Is an stage-permission related. Not wildcard-permission. As I've said, I've managed to perform queries on some domains, yet not having they explicitly on my permissions array.
The problem really lies on the type of script running.
The same script, if used as a popup, work'd fine. So, I've tried as an background-script with success too! I was facing the problem that devtools_page and related doesn't have such permissions...
The APIs available to extension pages within the Developer Tools window include all devtools modules listed above and chrome.extension API. Other extension APIs are not available to the Developer Tools pages, but you may invoke them by sending a request to the background page of your extension, similarly to how it's done in the content scripts.
http://developer.chrome.com/extensions/devtools.html
That level of script denies non explicit cross xhrs.
Solved the problem putting the requests in a background script and using messages api.
Thank you!

Resources