Request headers not passed when proxying with Apache HTTPD server - ajax

I have set up a proxy on Apache HTTP server for making the cross domain Ajax call. The call is happening but is returning a response indicating that the API key passed as a request header is invalid.
Can you make cross domain Ajax calls using Apache web server proxy? If so what am I doing wrong. ?
The proxy setting is as follows:
ProxyPass /api-temp/* http://api.temp.com/
The code to make the Ajax call is as follows:
var imageNamespace = {
imageUrls: [ ],
url: '/api-temp/v1/data/cat/42736286',
test: function() {
alert(234);
},
getImages: function() {
$.ajax({
type: 'GET',
dataType: 'json',
cache: true,
headers: {'API_KEY': 'xxxxxxxxxxxxxxxxxxxxxxxxx'},
url: imageNamespace.url,
success: function () {
alert('success:', success);
},
error: function (error) {
alert('ERROR:', error);
},
complete: function () {
alert('complete');
}
});
},
}
Here is the response in the browser:
The URL it is invoking is as follows: http://api.temp.com/v1/data/cat/42736286
Please enter valid API Key
I am passing the key in the request header but it is not being picked up. Any insight on how to resolve this will be helpful.

Related

trying to build http adapter from ajax request

i'm trying to build http adapter with token authorization form ajax request but get 401 error
Status Code:strong text
401 Unauthorized
missing_authorization
$.ajax({
type: "POST",
url: "https://abcd",
data: JSON.stringify({ "template": 1 }),
headers: { "Authorization": "xxxx", "Accept": "application/json",
"Content-Type": "application/json" }
});
function My_adapter() {
path = '/xxx';
var input = {
method : 'post',
path : path,
returnedContentType : 'json',
headers: {'Content-type':'application/json',
'Accept':'application/json', 'Authorization':'Token XXXXX'},
parameters: JSON.stringify({ "template": 1 }),
};
var result=WL.Server.invokeHttp(input);
return result;
}
tnx for your help,
sahar
The error message you see is expected. The client side code you posted shows that you are attempting to invoke MFP server outside of MFP client SDK ( jQuery ajax call). This call does not carry all the required information to the server and server sends the "missing_authorization" message as a result.
If you wish to invoke an adapter, use WLResourceRequest API provided by MFP client SDK. This takes care of handling the authentication handshake with MFP server. More details on the API usage here.

How to send push notifications in Chrome(Progressive Web Apps)

Please explain how to do push notifications with XHR and Javascript. or is there any other way to send push notifications in progressive web apps. I have created curl command and when i execute it in my terminal push notification sent but how to do it on button click?
Here is my cURL command:-
curl --header "Authorization: key=AIzaSxUdg" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"cxA-dUj8BTs:APAvGlCYW\"]}"
This is what i have tried :-
function send()
{
navigator.serviceWorker.ready
.then(function(registration) {
registration.pushManager.getSubscription()
.then(function (subscription) {
curlCommand(subscription);
$.ajax({
url: "https://android.googleapis.com/gcm/send",
headers: {
Authorization: "key=AIzaSxUdg",
},
contentType: "application/json",
data: JSON.stringify({
"registration_ids": [endpoint]
}),
xhrFields: {
withCredentials: true
},
crossDomain: true,
type:"push",
dataType: 'json'
})
.done(function() {
alert('done');
})
.fail(function() {
alert('err');// Error
});
})
})
}
But it shows error -----
XMLHttpRequest cannot load https://android.googleapis.com/gcm/send. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8880' is therefore not allowed access..
Google API is intended to be used from a server so it is not including CORS headers.
As you are performing a cross origin XHR (from your domain to Google's domain), the User Agent makes a preflight request in search of the CORS headers that tell your client is authorized to perform operations.
To do this you need to make a request to your server (i.e. a POST on /notifications/send) and your server should then execute the cURL request to GCM.
This will work:
function send()
{
navigator.serviceWorker.ready
.then(function(registration) {
registration.pushManager.getSubscription()
.then(function (subscription) {
curlCommand(subscription);
$.ajax({
url: "https://cors-anywhere.herokuapp.com/https://android.googleapis.com/gcm/send",
headers: {
Authorization: "key=AIzaSxUdg",
},
contentType: "application/json",
data: JSON.stringify({
"registration_ids": [endpoint]
}),
xhrFields: {
withCredentials: true
},
crossDomain: true,
type:"push",
dataType: 'json'
})
.done(function() {
alert('done');
})
.fail(function() {
alert('err');// Error
});
})
})
}

How to enable CORS?

I'm making a request from client side to a web-API on different domain to extract data in JSON format. How do I enable Cross Origin Resource Sharing(CORS)?
Client runs on https while my web-API runs on http.
This is the AJAX call that I'm making :
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://map.techriff.in/api/values",
success: function (json) {
console.log(json);
},
error: function (err) {
console.log(err);
}
});
});
This site helped me when I had an issue with Chrome showing the following error: "No 'Access-Control-Allow-Origin' header is present on the requested resource"
Go down to the section titled "Enable CORS".
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Note, I used the following attribute syntax as opposed to what was listed in the site above:
[EnableCors("http://localhost:1616", "*", "*")]
You need to add the Access-Control-Allow-Origin: http://domain.com to your response header, where domain.com is replaced with the domain you want to allow (don't use * wildcards).
How you do this depends one your server stack. In ASP.NET:
Response.AppendHeader("Access-Control-Allow-Origin", "http://domain.com");
You then need to set $.support.cors = true in your jQuery to enable it on the client.
Add $.support.cors = true; somewhere before to make your $.ajax call.
Source: Is it safe to use $.support.cors = true; in jQuery?
Assuming you correctly set the Access-Control-Allow-Origin header on the server as well.
CORS jQuery AJAX request
First of all, this is a big issue. Everyone will say you have to enable CORS in the server. What if we are requesting an API?. What I did is.
Step 1: Make an ajax call to my own server.
Step 2: Make https request from my server to the API.
Step 3: Send the result to the ajax.
My AJAX call.
$.ajax({
type: "POST",
url: "makepay",
data:{
key:value
},
success: function(response) {
//place to handle the response
},
error: function() {
//place to handle the error
}
});
My server page
const https = require('https');
app.post('/makepay',function(req, res){
var options = {
host: "Site address",
path: "Path",
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
var req = https.request(options, (resp) => {
resp.on('data', (xmlresponse) => {
res.send(xmlresponse);
}}
req.write(parameters_to_the_API);
req.end();
});
I hope you will get at least the idea.

How to show AJAX response message in alert?

I am sending username and password as request parameter to the server in AJAX and trying to show the response message. But not able to showing the response message.In fiddler it is showing the response message. But while on the browser screen it is not showing.PLEASE somebody help me out where i am wrong or need to change anything..
I have written like this-
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://test.xyz.com/login",
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: { username: "abc", password: "1234" },
dataType: "JSONP",
jsonpCallback: 'jsonCallback',
async: false,
success: function (resdata) {
alert(resdata);
},
error: function (result, status, err) {
alert(result.responseText);
alert(status.responseText);
alert(err.Message);
}
});
});
});
TL;DR: I guess the problem is on the server side of your code (that we don't know yet).
At first: I don't know why it fails for you. I've taken your code and ran it against a public available JSONP API, that returns the current IP of your system and it worked.
Please try yourself using the URL: http://ip.jsontest.com/.
So most probably, the server doesn't return the right response to the JSONP request. Have a look at the network tab in developer tools. With your current code, the answer of the server should be something like:
jsonCallback({'someResponseKeys': 'someResponseValue'});
Note: The header should contain Content-Type:application/javascript!
BTW, even if this doesn't for now solve your problem - here are some tweaks, I'd like to advice to you:
Don't set async to false, at the documentation of jQuery.ajax() says:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous
operation.
You don't need to set a jsonpCallback, because jQuery will generate and handle (using the success function a random one for you. Quote from the docs:
This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling.
So here comes my code:
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://ip.jsontest.com/",
crossDomain: true,
data: { username: "abc", password: "1234" },
dataType: "JSONP",
success: function (resdata) {
console.log("success", resdata);
},
error: function (result, status, err) {
console.log("error", result.responseText);
console.log("error", status.responseText);
console.log("error", err.Message);
}
});
});
});
A working example can be found here.
Another solution, like Yonatan Ayalon suggested, can be done with a predefined function and then setting the jsonpCallback explicitly to the function that should be called.
if you see the response in Fiddler, it seems that the issue is in the callback function.
you are doing a jsonP call - which means that you need a callback function to "read" the response data.
Do you have a local function that calls "jsonCallback"?
this is a simple jsonP request, which initiates the function "gotBack()" with the response data:
function gotBack(data) {
console.log(data);
}
$.ajax({
url: 'http://test.xyz.com/login' + '?callback=?',
type: "POST",
data: formData,
dataType: "jsonp",
jsonpCallback: "gotBack"
});
You can try with the following methods and close every instance of chrome browser in task manager, then open browser in web security disable mode by the command "chrome.exe --disable-web-security"
success: function (resdata) {
alert(resdata);
alert(JSON.stringify(resdata));
},
And the better option to debug the code using "debugger;"
success: function (resdata) {
debugger;
alert(resdata);
alert(JSON.stringify(resdata));
},

Ajax returning 404 error on ASP MVC3 site

This Ajax code works perfectly is I'm running the program on my local machine. However, once we put this out on a DEV server we get a 404 error. The site is an ASP MVC3 site that communicates with a SQL database, and the rest of the site has no problem doing so. I'm brand new to Ajax so I'm not quite sure where to look. Could this be an issue with IIS as well?
Ajax code
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { 'programName': pgmname },
dataType: 'text',
success: function (data) {
console.log(data);
alert(data);
//$('#data').dialog('open');
},
error: function (data) {
console.log(data)
alert("Unable to process your resquest at this time.");
}
});
Chrome's Console error message:
POST http://insideapps.dev.symetra.com/BatchPrograms/PopDetails 404 (Not Found)
send jquery-1.8.3.js:8434
jQuery.extend.ajax jquery-1.8.3.js:7986
GetProgramDetails BatchDashboard:51
onclick BatchDashboard:165
Chome's Network error message
Name (Path) Method Status (Text) Type Initiator Size Time (Latency)
PopDetails POST 404 Not Found Text/Html jquery-1.8.3.js:8434 1.8KB 21ms
/BatchPrograms Script 1.6KB 17ms
Try modifying url to
url: '#Url.Action("PopDetails", "BatchPrograms")'
Try using the Url.Action() helper to get the route from the Table Routes defined in your application.
var request = $.ajax({
type: 'POST',
url: '#Url.Action("PopDetails", "BatchPrograms")',
data: { 'programName': pgmname },
dataType: 'text',
success: function (data) {
$('#data').dialog('open');
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});

Resources