http request going over https server in laravel ajax - ajax

I am trying to get some data using ajax in laravel project.
i have https domain but when the ajax request is made it is made over http.
So the ajax request gives a mixed content error and also a https request for same is showed cancelled.
i have already added to app service provider
if(config('app.env') === 'production') {
\URL::forceScheme('https');
}
main ajax setup with url formation
let url = '/opportunities/?' + $('#opportunity_search_form').serialize();
if(window.location.search && !this.initialLoaded){
url = url + '&' +window.location.search.substring(1);
}
url = url + '&page=' + self.pageCtr
$.ajax({
url: url,
type: "get",
beforeSend: function(xhr, type) {
if (!type.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
}
})
in the above image first request that shows cancelled goes over https ... and the other goes over http with mixed content error..i don't know how it is being sent .
Also i tried creating url using
let url = window.location.protocol + '//' + window.location.hostname + '/opportunties/' + other parameters
Thankyou.

Related

Sharepoint How to do get request to external web service

How can I make get request from Sharepoint object model to external web service? I tried did it with ajax request:
$.get("http:/servername/webservice_name", function(data, status) {
alert("Data: " + data[0] + "\nStatus: " + status);
});
But I have an error: Access denied.
My web service has response in JSON format.
I have read a lot of article, but there are no decisions. I read, that ajax forbidden in SharePoint for external web service. How can I make it without ajax?
If you believe that the use of AJAX or a specific library is preventing you from accessing the web service, you can try invoking the web service directly using a native JavaScript XMLHttpRequest.
For example:
var verb = "GET";
var url = "http://servername/webservice_name";
var xhr = new XMLHttpRequest();
xhr.open(verb, url, true);
xhr.setRequestHeader("Content-Type","application/json");
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
myCallbackFunction(xhr.status, xhr.responseText);
}
};
xhr.send(data);
function myCallbackFunction(status, text){
// do something with the results based on the status
}
You should also confirm that your Internet Explorer settings are the same for SharePoint as they are for the HTML page where you're able to get the web service to work. Specifically, you'll want to check the browser mode and security settings.
Confirm that the problem still exists when the settings are identical before trying to troubleshoot your network or code.
In the SharePoint online it is work only for https web services. http from https web sites not allowed.
Final code, which work with https:
$(document).ready(function(){
$.ajax({
url: "https://services.odata.org/Northwind/Northwind.svc/Customers",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
async: false,
success: function (data) {
if(data.d.results.length>0){
alert("Results Count:"+data.d.results.length);
}else{
alert("no data");
}
},
error: function () {
//alert("Failed to get details");
}
});
});

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);

Angularjs and Web Api - JSON formatting issue

I have a lightweight Angularjs app and I'm trying to process json from my ASP.NET Web Api controller.
In the angularjs factory:
adapter.getLegacyCouriers = function(id) {
return $http({
method: 'GET',
url: 'http://legacywebapi.azurewebsites.net/api/legacycourier'
});
}
In the controller:
legacyService.getLegacyCouriers()
.success(function (response) {
alert("Success: " + JSON.stringify(response));
})
.error(function (response) {
alert("Error: " + JSON.stringify(response));
});
When I exchange the URL in the $http get with this one it hits the success block. However, my default URL which returns json formatted in the same way hits the error block.
Can someone help me? Both returns application/json response headers, and both return a status of 200 OK (using Chrome to debug). I can't figure out why my json is hitting the error block.
Your service responing with
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'run.jsbin.com'; is therefore not allowed access.
from your legacywebapi.azurewebsites.net/api/legacycourier
please see here jsbin.com/nugif/1/edit.
Just enable cross-origin resource sharing.

Error when calling node.js from client side using $.ajax

I'm trying to make an Ajax call from my client like that:
$.ajax({
url: '/item/' + id + '/action?parameter=' + parameter,
method: 'GET',
success: function(data) {
.....
}
});
and the error I'm getting is:
500 (Internal Server Error) (from the Azure server
(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+""); (highlight)
The rest of the site is working well, only the ajax call returs the error (tried also with POST)
In my server, I've done few attempts:
1)
cors = require('cors'),
path = require('path');
var app = express();
app.use(cors());
2)
exports.action= function(req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
But still getting the error

AJAX HEAD request for offsite file/directory

I have an AJAX call that check to see if a file exists. Success displays the file, failure doesn't. Troubleshooting the type: HEAD, property of AJAX. It prefixes the called URL with the domain of the scripts origination.
$(document).ready(function(){
var agentuid = $('#agentuid').val();
var imgurl = 'http://www.universaldynamicmedia.com/sandbox/singleprop_img/agencies/' + agentuid + '.png';
var img = '<img id="firm_pic" src="' + imgurl + '" />';
$.ajax({
url: imgurl,
type:'HEAD',
error: function() {
$('#firmlogo').append('<h1>FAIL!</h1>');
},
success: function() {
$('#firmlogo').html('<h1>SUCCESS!</h1>');
}
});
});
When it tries to find the url as defined in var imgurl, it kicks back an error with this:
XMLHttpRequest cannot load http://theimgurl.com/image1.png Origin http://www.therequesturl.com is not allowed by Access-Control-Allow-Origin.
Is there a way to cross domain a HEAD request?
When your request is successful there is no content to restrict you from (because of the head request), but when you get an error an error document is sent (I've only checked this in Apache) so then there is content to block due to SOP. http://jsfiddle.net/mowglisanu/DGa7V/5/

Resources