How to enable CORS? - ajax

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.

Related

How to perform a Ajax Request via browser to AWS API Gateway with CORs Policy?

I performed a GET request via Postman successfully, but it is failing in the browser due to CORs
I've tried both XHR and Jquery Ajax (see codepen here), and I've also set Access-Control-Allow-Origin
XHR
var data = "{\"value\":'174.9',\"time_stamp\":\"2019-10-01T18:56:45-04:00\",\"date\":\"2019-10-01\",\"name\":'weight',\"category\":'weight'}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://f17c15m5a79.execute-api.us-east-2.amazonaws.com/production/quantified-self-metrics");
xhr.send(data);
Jquery Ajax
var settings = {
async: true,
crossDomain: true,
url:
"https://f17c15m5a79.execute-api.us-east-2.amazonaws.com/production/quantified-self-metrics",
method: "GET",
headers: {
"Access-Control-Allow-Origin": "*"
},
data:
'{"value":\'175.9\',"time_stamp":"2019-10-02T18:56:45-04:00","date":"2019-10-02","name":\'weight\',"category":\'weight\'}'
};
$.ajax(settings).done(function (response) {
console.log(response);
});
The response I receive from the browser is the following:
Access to XMLHttpRequest at
'https://f17c15m5a79.execute-api.us-east-2.amazonaws.com/production/quantified-self-metrics?{%22value%22:%27175.9%27,%22time_stamp%22:%222019-10-02T18:56:45-04:00%22,%22date%22:%222019-10-02%22,%22name%22:%27weight%27,%22category%22:%27weight%27}'
from origin 'https://codepen.io' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
I've also implemented the solution found in this question
You need to prepend https://cors-anywhere.herokuapp.com/ to your request url.
So it will look like https://cors-anywhere.herokuapp.com/https://f17c15m5a7.execute-api.us-east-2.amazonaws.com/production/quantified-self-metrics

Plivo SDK call Recording

I am getting an error that i dont understand an cannot find any helpfull informations about:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https:*******' is therefore not allowed access. The response had HTTP status code 401.
function RecordTheCall()
{
var key = '*******************';
$.get( "https://api.plivo.com/v1/Account/"+key+"/Call/?status=live", function( data ) {
var callUuid = data.call_uuid
});
$.ajax({
url: "https://api.plivo.com/v1/Account/"+key+"/Call/"+callUuid+"/Record/",
type: "POST",
data: { 'auth_id': auth_id, 'call_uuid': CallUUID },
dataType: "json",
success: function (res) {
alert(res);
},
error: function(err) {
alert(err);
}
});
}
Call recording cannot be accomplished from the Web SDK directly. You cannot use the Plivo API from your Web browser using Javascript because cross-domain ajax requests are not allowed in browsers for security reasons.
This has been explained in this Wikipedia article. There are some work arounds to overcome this, but it is browser dependent and hence it might not work always. Instead you should use the Plivo XML/API in you application.

simple ajax request to localhost nodejs server

I wrote very simple server :
/* Creating server */
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
/*Start listening*/
server.listen(8000);
I run it using nodejs.
Now i want to write simple client that use ajax call to send request to server and print response (Hello World)
Here javascript of clinet:
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/" ,
success: function (data) {
console.log(data.toString);
}
});
When I open client html file i get following error in console:
XMLHttpRequest cannot load http://127.0.0.1:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I tried adding to ajax call following:
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/" ,
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
console.log(data.toString);
}
});
But then i get
Resource interpreted as Script but transferred with MIME type text/plain: "http://127.0.0.1:8000/?callback=jQuery211046317202714271843_1410340033163&_=1410340033164".
Anyone can explain what i did wrong and perhaps how to fix it?
Many thanks!
To overcome the CORS, in your node.js file write the below, based on what you need:
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
The first error is caused by CORS (Cross Origin Resource Sharing) policy. It's rule by all browsers that you cannot make a request to a remote server in AJAX other than to the current server the script/page was loaded from unless that remote server allows it via Access-Control-Allow-Origin header.
I suggest serving the page from the same Node.js server. Then it will work. Example, when the request comes to root / page, then serve the index.html file, otherwise, server whatever other content you want.
var http = require('http'),
fs = require('fs');
/* Creating server */
var server = http.createServer(function (request, response) {
if (request.url == '/' || request.url == '/index.html') {
var fileStream = fs.createReadStream('./index.html');
fileStream.pipe(response);
} else {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
}
});
/*Start listening*/
server.listen(8000);

Request headers not passed when proxying with Apache HTTPD server

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.

How to do a simple http get ajax style using mootools 1.2.1

I'm trying to do a simple ajax GET that returns the html from google.com but with the following I keep hitting my onFailure. And when I hit status i get a 0, yet when I attempt to output the responseText I get nothing.
Anyone done a simple request like this in mootools 1.2.1?
function addSomeAction() {
el.onclick = function() {
var uri = "http://www.google.com";
var myRequest = new Request({
url: uri,
method: 'get',
onRequest: function(){
alert("loading...");
},
onSuccess: function(responseText){
alert("hi");
},
onFailure: function(responseFail){
alert("fail: " + responseFail.responseText);
}
});
myRequest.send();
}
}
Regardless of the framework used, you cannot do cross-domain AJAX requests. This is to prevent Cross-Site Request Forgery (CSRF) attacks and is a limitation imposed by the web browser.
Therefore, you can only fetch the HTML source of a page which on the same domain as the originating request.
There are specifications allowing for the asynchronous transfer of JSON data residing on another domain (JSONP), but they will not help you in this case.

Resources