Unable to send cross-domain request in `Firefox` extension - javascript

I am trying to access cross-domain data by using jsonp or XMLHttpRequest with GET method. My Code:
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/ajax.php?code=BSE", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
xhr.send();
JsonP
$.ajax({
type: 'GET',
url: "http://example.com/ajax.php?code=BSE",
dataType: "jsonp",
jsonpCallback: "jsonp_callback",
crossDomain: true,
success: function(res){
console.log(res);
}
});
Both methods having same behavior. Whenever i am sending request its just keep loading (even i am not sure its sending request or not) and do nothing.
And my php code:
PHP Code:
header('content-type: application/json; charset=utf-8');
$dts=array('value'=>'123');
echo $_GET['jsonp_callback'] . '('.json_encode($dts).')';

The XMLHttpRequest will work just fine, no need for jsonp. In your manifest.json, make sure you request permissions for the domain you are posting to -- Chrome doesn't require permissions for XHR, but Firefox does. This error manifests in Firefox as a http code 404 in the XHR, but no activity in the network panel. If you get a http code 0, you have CORS or mixed content security issues as well.
{
"manifest_version": 2,
"name": "web extension",
"version": "1",
"permissions": [
"http://example.com/"
],
"content_scripts": [
{
// ...
}
]
}

Try using new XDomainRequest() in your xhr request. XDomainRequest is an implementation of HTTP access control (CORS).
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'http://example.com/ajax.php?code=BSE';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
};
xhr.onerror = function() {
// Error code goes here.
};
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.send();

Related

how to call a service using ajax javascript?

I'm learning programing, could you explain me how to call a service using ajax javascript?
Service information:
Service type: REST
Basic authentication
Estructure: Application/JSON
Url: https://osb.urosario.edu.co/uxxi-URO/WsFotografias/proxy/AdministradorFotografiasJsonPS/fotos/consultar
User: Admi
Password: admi
Parameter JSON example: {"identificacion":["98122811999"]}
I've tested this service in postman
Service answer:
{
"respuesta": [
{
"estado": "Correcto.",
"identificacion": "98122811999",
"imagen": "return string Base 64 format"
}
]
}
Using JQuery :
$.ajax({
type: 'POST',
url: 'https://osb.urosario.edu.co/uxxi-URO/WsFotografias/proxy/AdministradorFotografiasJsonPS/fotos/consultar',
dataType: 'json',
data:{"identificacion":["98122811999"]}
contentType: "application/json"
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth("admi", "admi"));
},
success: function (data,status) {
//do what you want with the data after success
//in this example the response will be promoted in the browser console
console.log(data);
});
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
You can call your above RestEndpoint using below:
xmlhttp.open("POST", "/EndpointURI", true);
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
//Use parse() method to convert JSON string to JSON object
var responseJsonObj = JSON.parse(this.responseText);
//use response
}
};
var jsonData = {"name" : "yourData"};
xmlhttp.send( JSON.stringify( jsonData ) );
For Authentication use this:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://EndPointURI", true);
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('userName:password'));
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send();
For authentication part, use JQuery then it will easy for the implementation and as well for understanding. as now aday no body use basic xmlhttp for calling api in javascript, last time i used was a 2003 developed application.

Post metafields to shopify admin API

I´m trying to save customers metafields using the shopify admin api, i´m using this code
var data = {
"metafield": {
"namespace": "test",
"key": "testkey",
"value": "lorem ipsum",
"value_type": "string"
}
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/customers/0000000000/metafields.json", true);
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('myuser:mypass'));
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send(JSON.stringify(data)); //RETURNS A CODE 301 WITHOUT RESPONSE MESSAGE
xhr.send(data); //RETURNS A CODE 400 WITH "error 419: unexpected token at 'object Object]'" MESSAGE
Please tell me What I missing?
Thanks a lot
It looks like you are trying to save the metadata to customer id 00000000 in your URL, typically you'll want to have that field supplied dynamically if this is going to be used in a utility tool. Your probably might be that ID is not pointing at an actual customer ID.

SyntaxError: JSON Parse error: Unexpected EOF using TVJS Framework

I am building a TVML application for Apple TV. When I run this code to make a request to a remote server I get this error: SyntaxError: JSON Parse error: Unexpected EOF. I am trying to run the code from the application.js file and populate the applications inital view. Any help is appreciated.
loadData("https:/xxx.xxx.net")
function loadData(url) {
var xhr;
var jsonData;
xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.onreadystatechange = function() {
if (xhr.status == 200) {
jsonData = JSON.parse(xhr.responseText);
console.log(jsonData);
};
};
xhr.open("GET", url, true);
xhr.send();
if (jsonData != undefined) { return jsonData }
};
Other devices like Roku use the same api and function correctly.
{
"playlists": [
{
"id": 8,
"title": "test",
"description": "new playlist test",
"cover_url": "http://598-1446309178.png"
},
{
"id": 9,
"title": "test1",
"description": "lives",
"cover_url": "http://754-1446309324.jpg"
},
{
"id": 10,
"title": "test2",
"description": "video games",
"cover_url": "http://6173-1446310649.jpg"
},
{
"id": 11,
"title": "test4",
"description": "little",
"cover_url": "http://dd6-1446312075.jpg"
}
]
}
You can debug your app using Safari.
Once your app is running, choose "Develop / Simulator / {your app}".
That part of your code looks OK, but check what xhr.responseText is, it may return empty.
Your other error is that you are making an async request when you use "true" below:
xhr.open("GET", url, true);
You need to supply a callback to your function and use that callback.
I am using error first callback style.
function loadData(url, callback) {
var xhr;
var jsonData;
xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.onreadystatechange = function() {
if (xhr.status == 200) {
try{
jsonData = JSON.parse(xhr.responseText);
} catch(e) {
return callback('json parsing error');
}
callback(null, jsonData);
console.log(jsonData);
};
};
xhr.open("GET", url, true);
xhr.send();
};

No Access-Control-Allow-Origin header is present on the requested resource when calling WebAPI

I'm trying to call my WebAPI, but I'm always get the error No Access-Control-Allow-Origin header is present
Following the Using Cors article, we have the code below, but it always falls onerror method
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://localhost:56280/api/Meta/GetListMetas';
var xhr = createCORSRequest('GET', url);
xhr.withCredentials = true;
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function () {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function () {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
I've tryied the JSONP also but without success again, falls on error method
$.ajax({
type: "GET",
dataType: 'jsonp',
url: "http://localhost:56280/api/Meta/GetListMetas"
}).success(function (data) {
alert(data)
}).error(function (da) {
});
WebAPI
I made a pretty simple API to do the sample
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Controller
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class MetaController : ApiController
{
public string GetListMetas()
{
return "1";
}
}
I've tryied serialize the return also, bu without success.
Someone can help me ?
UPDATE
Below, I attach the request header
The problem, as Vaughn Okerlund mentioned, is in the request made by the client.
The request is blocked by the server cause it does not recognize the client's request.
You can enabled the origin white-listing the domain where the client is running:
public static void Register(HttpConfiguration config)
{
var corsAttr = new System.Web.Http.Cors.EnableCorsAttribute("http://localhost:7185", "*", "*");
config.EnableCors(corsAttr);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
As you can see I've enabled all the request for every verb from this domain:
http://localhost:7185
If you configure everything there you don't need
[EnableCors(origins: "*", headers: "*", methods: "*")]
on your controller.
Considering your client is hosted in http://localhost:7185/ you can use jQuery to call the server simply using this syntax:
$.ajax({
type: 'GET',
url: 'http://localhost:56280/api/Meta/GetListMetas',
data: {},
dataType: "json",
// crossDomain: true,
success: function (result) {
alert(result);
},
//complete: function (jqXHR, textStatus) {
//},
error: function (req, status, error) {
alert(error);
}
});
Looking here, it seems the issue is that in your controller's response to the service's request you're sending the wildcard header (*) for the origin rather than specifying a domain to allow. In order to send a credentialed request, the server has to grant access to a specific domain:
Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding. The above example would fail if the header was wildcarded as: Access-Control-Allow-Origin: *. Since the Access-Control-Allow-Origin explicitly mentions http://foo.example, the credential-cognizant content is returned to the invoking web content. Note that in line 22, a further cookie is set.

CORS: Access-Control-Allow-Origin not equal to supplied origin

I'm trying to send an email from an application using sendgrid. This shouldn't be too difficult, and with PHP I've sent emails before. In this case I want to do it in Javascript as it's part of an Ember application. The first problem is the "No 'Access-Control-Allow-Origin" message, which I tried to solve with CORS. Now I've just got a different error!
Now I'm not sure where to look for tackling this issue. The code I'm using is the following:
(function(){
makeCorsRequest('GET', mailUrl);
})();
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function makeCorsRequest(type, url) {
var xhr = createCORSRequest(type, url);
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.onload = function() {
var text = xhr.responseText;
console.log(text);
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
This gives me the error:
The 'Access-Control-Allow-Origin' header has a value 'https://sendgrid.com' that is not equal to the supplied origin. Origin 'http://localhost' is therefore not allowed access.
sendGrid CORS policy does not allow browsers to call their API (except if your are on "sendgrid.api-docs.io" domain) ... You have to send email from your server,
but if just for test or development purpose you can use my demo on github
https://github.com/itisnajim/sendgrid-nodejs
post your data to
http://sendgrid-nodejs-oxailstudiosnode.7e14.starter-us-west-2.openshiftapps.com
Ajax example:
let urlStr = "http://sendgrid-nodejs-oxailstudiosnode.7e14.starter-us-west-2.openshiftapps.com";
const msg = {
"personalizations": [
{"to": [{"email": "example1#mail.com"}]}
],
"from": {"email": "example2#mail.com"},
"subject": "subject example",
"content": [{"type": "text/plain", "value": "example body text"}]
};
$.ajax({
url: urlStr,
type: 'post',
data: JSON.stringify(msg),
dataType: 'json',
contentType: "application/json; charset=utf-8",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer API_KEY_HERE")
},
success: function(data){
//console.log(data);
//OK: Mail sent!!
},
error: function( jqXhr, textStatus, errorThrown ){
//console.log( errorThrown, textStatus, jqXhr );
if(jqXhr.status === 202 || jqXhr.status === "202"){
//OK: Mail sent!!
}else
console.error("Mail not sent! Err:"+JSON.stringify(errorThrown))
}
})
It looks like you're calling the SendGrid API from an Ember app running in your browser? If so, you probably shouldn't be (for a number of security reasons).
You'll want to make an AJAX request to a server running on your own domain, and have your server
validate that the request is legitimate, and
call the SendGrid API to send the email
Exposing your SendGrid API key, and calling the API directly from a browser exposes your SendGrid account to potential abusers.
For the server-side API call, check out SendGrid's API Clients. You shouldn't need to write the API calls yourself.

Categories

Resources