AJAX GET requests with Varnish Cache - ajax

I have got an AJAX request running on a server with varnish. The request is as follows:
(function() {
$("#name").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'GET',
url: php_vars.var_1, //your server side script
dataType: 'json',
data: {
postcode: request.term
},
success: function (data) {
alert("Success");
}
});
}
});
})();
For the url, I use wp_localize_scripts and array with the absolute URL of the php script. I have consoled this url before this script and it is ok.
I have this setup on a server not running with varnish and it works fine. However on my server with varnish, I have noticed that the request URL is not correct (should be "auspost.php" and instead it is the page url with the query params). On my none varnish server the GET request url is correct.
It looks like varnish is caching my GET requests. Any advice would be very much appreciated! I can pastebin my vcl config if need be?

For ajax requests you should have the following header available
X-Reqeusted-With: XMLHttpRequest
In your varnish vcl_recv you can check if this header is present and force a pass.
if (req.http.X-Requested-With == "XMLHttpRequest"){
return (pass);
}

Related

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 use ajax to trigger jenkins job build?

I'm writing a web page to let others can trigger the some jobs' build with parameters in jenkins. So I use ajax to send POST request:
var urlString = "http://localhost:8080/job/myjob/buildWithParameters";
$.post(
urlString,
{myParam:"there is some data"},
function(data)
{
alert(data);
},
"json"
);
But I got Http 403 response:
XMLHttpRequest cannot load http://localhost:8080/job/myjob/buildWithParameters. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 403.
I know the cross site problem , but I cannot search any helpful information from Google, can ajax do this job?
UPDATE:
I found a similar question
So I update my code to :
$.ajax({
type: "POST",
url: urlString,
dataType: 'jsonp',
data: {},
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Basic " + btoa("admin:123456"));
},
success: function(data) {
},
complete: function(xhr, statusText){
}
});
I can confirm the username and password is correct , but I got 405 Method Not Allowed. Is there anything wrong?
Put your web page in the userContent folder under $JENKINS_HOME directory. Then open $JENKINS_URL/userContent/yourwebpage.html in your browser. Now the javascript in the page is loaded from the same origin where ajax calls will go, so it should be allowed without CORS tricks.
Jenkins want a POST not a GET HTTP request, a JSONP request is a GET: you can't do that :D
You can try to do in these way:
Startup jenkins with the AJP binding as described here
Configure Apache2 httpd as a reverse proxy for the Jenkins AJP
Force in Apache2 response header as described here to enable CORS
At the end you can use directly POST instead of JSONP.
have fun with XSS :D

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

Logging into an expressjs app with CORS

I have expressjs sitting on a nodejs server and I have a client side cordova app making ajax requests to certain routes.
This is fine until I need to make a POST request to login using passportjs, there is a 302 redirect that takes place so I get this 302 Moved Temporarily when making this call
$('body').on('submit', '#logIn', function(e){
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: "http://mydomain.io:3300/login",
data: JSON.stringify(formData),
type: "POST",
crossDomain: true,
dataType: "json",
async: true,
success: function(response){
alert('succeeded!');
console.log(response);
alert(response);
},
failure: function(message){
alert("failed");
console.log(message);
alert(message);
}
});
});
So my question is how is it possible using CORS to login to the app using client side ajax?
CORS is not your problem here.
Passport wants to redirect your user (based on the values you've passed to passport.authenticate). For instance:
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/',
failureRedirect: '/login' }));
Passport will tell the browser to redirect to / or /login by returning a 302. You can remove the redirect by removing the second parameter to passport.authenticate:
app.get('/auth/facebook/callback',
passport.authenticate('facebook'));
This will call next() on successful authentication (and return 401 otherwise).
The examples here use FacebookStrategy, but it works with any strategy.

crossdomain $.ajax and 404 error

I want to retrieve some data using $.ajax from the external ASP.NET MVC site (in this case - from my site). The code below geive me a 404 Not Found error (of course the url is valid.
But, if I change the url from url: 'http://myurl.com/Home/GetMyCode/?id=mycode' to url: 'http://localhost:123/Home/GetMyCode/?id=mycode' everything is fine. So, how to fix it ?
$.ajax({
url: 'http://myurl.com/Home/GetMyCode/?id=mycode',
type: 'POST',
contentType: "application/json; charset=utf-8",
crossDomain: true,
success: function (res) {
...
},
error: function (jqXHR, textStatus, errorThrown) {
...
}
});
[HttpPost]
public JsonResult GetMyCode(string id)
{
try
{
return Json(new { result = "ok", resultData = "OK") });
}
catch (Exception e)
{
return Json(new { result = "error", resultData = "An error occured" });
}
}
Two Methods for Handling Cross-Domain Ajax Calls:
JSONP: The Current Standard for Cross-Domain Access
JSONP is a convention used by some sites to expose their content in a way that makes it easier for callers to consume data via script, even from an external domain. The trick consists in having the site return some JSON content not as a plain string but wrapped up in a script function call. For more details..
http://www.west-wind.com/weblog/posts/2007/Jul/04/JSONP-for-crosssite-Callbacks
http://www.jquery4u.com/json/jsonp-examples/
Cross-origin resource sharing (CORS)
To enable cross-domain requests in environments that do not support cors yet but do allow cross-domain XHR requests (windows gadget, etc), set $.support.cors = true;
You just tell jQuery that you're in an environment where Cross-Domain XHR requests are possible.
In order to retrieve data crossdomain, you probably need to use 'jsonp'
Looks like it might be a DNS issue. Are you able to get to: http://myurl.com ?
Is the .com domain you are trying to access publicly accessible? Or is it a loopback to localhost?
that tutorial worked for me, I had to implement the JSONP handling in my MVC project. http://www.codeguru.com/csharp/.net/net_asp/using-jsonp-in-asp.net-mvc.htm

Resources