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.
Related
I am testing a local HTML Form sending data to an aspx application as backend. Since I have some problem with CORS (even on localhost) I am trying to emulate the Ajax request performed by jQuery with NodeJS. I don't know if this is the right way to do. In the HTML form, after the jQuery validation, this is what I do:
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
console.log(response);
}
});
//console.log($(form).serialize())
}
and it works, until CORS ends the request. I mean that I can retrieve the data from the backend application.
Instead, if I do:
function loadDoc() {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhttp = new XMLHttpRequest();
/*var FormData = require('form-data');
var myform = new FormData();
myform.append('firstname', 'foo');*/
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("POST", "http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE", true);
//which is the same string I get from .serialize() in jQuery
xhttp.send("firstname=foo&email=some#domain.it");
}
loadDoc();
I cannot get anything from the server application. If I want to get the parameter firstname from the POST data, I get null. So, where am I wrong?
UPDATE
This is the only workaround I have found useful in NodeJS:
var http = require('http');
var querystring = require('querystring');
var post_data = querystring.stringify({'firstname':'Lory'});
var post_options = {
host: 'localhost',
port: '1308',
path: '/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_data)
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
// post the data
post_req.write(post_data);
post_req.end();
I had also tried with:
var request = require('ajax-request');
request.post({
url: 'http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
data: {'firstname':'Lory'},
headers: {}
}, function(err, res, body) {
console.log(res);
}
);
but it did not work too. I feel such an ignorant and I would like to know the differences between those 3 libraries.
I have some doubts concerning the fact I must use querystring.stringify() in the working solution, because POST data are not in the URL and should not be uder the limits of query string, if I remember well.
I would like to suggest request module. while doing ajax call post, we can post the data by form or JSON format. It's based on receiver end point how they are receiving.
I hope you are trying to post form data.
var request = require('request');
request.post({
url:'http://service.com/upload',
form: {'firstname':'Lory'}
}, function(err,httpResponse,body){
/* ... */
})
If you are trying to do normal JSON post.
var request = require('request')
request({
method: 'POST',
uri: 'http://www.google.com',
body:{'firstname':'Lory'}
}, function(err,httpResponse,body){
/* ... */
})
request module provide lots of options. Play with that then you will get the better idea.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm" name="myForm">
<div>
<label for="comment">Comment:</label>
<textarea id="comment" name="comment"></textarea>
</div>
<div>
<label for="rating">Comment:</label>
<textarea id="rating" name="comment"></textarea>
</div>
<input type="submit" value="Submit!">
</form>
<script>
$(document).ready(function () {
$('form').submit(function (event) {
event.preventDefault();
//collect the form data using Id Selector what ever data you need to send to server
let comment=$('#comment').val();
let rating= $('#rating').val()
$.ajax({
url: 'replace your url',
data: JSON.stringify({"comment": comment, "rating": rating }),
processData: false,
type: 'POST',
contentType: 'application/json',
success: function (data) {
alert(data);
}
});
});
})
</script>
</html>
I am trying to send an audio blob over to my Rails action through an ajax POST. I seem to get over to the Rails action but the data I am sending appears to be empty and my audio file is not saved. I can do this with simple javascript, but I cannot seem to get this to work with ajax.
Ajax not working:
function sendRecToPostAjax(blob){
var data = new FormData();
data.append("audio", blob, (callid + ".oga"));
data.append('callid', callid);
return $.ajax({
url: '/controller/action',
type: 'POST',
cache: false,
data: data,
processData: false,
contentType: false
});
}
JS working:
function sendRecToPost(blob) {
var data = new FormData();
data.append("audio", blob, (callid + ".oga"));
data.append('callid', callid);
var oReq = new XMLHttpRequest();
oReq.open("POST", "/controller/action");
oReq.send(data);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
console.log("Uploaded");
} else {
console.log("Error " + oReq.status + " occurred uploading your file.");
}
};
}
This jQuery code is working:
$.ajax({
type: "POST",
url: "file.php",
data: { json: json },
complete: function (data) {
var result = data.responseText;
console.log(result); // logs 'echo' from PHP file
}
});
This JavaScript code is still not working:
var xhr = new XMLHttpRequest();
xhr.open("POST", "file.php", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result); // supposed to log 'echo' from PHP file
}
}
xhr.send(JSON.stringify(json));
Aren't these two approaches equivalent, or am I missing something?
Suppose 'file.php' looks something like this:
if(isset($_POST['json'])){
$obj = json_decode($_POST['json']);
//some php operation
// echo $obj keys and values
}
data : { json: json }
gets serialized to '{ "json": {data} }'
JSON.stringify(json)
gets serialized to '{data}' and there is no "json" key
add your javascript object to a parent wrapper object with a "json" key
JSON.stringify({ json: json });
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.
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.