server response ajax request angular - ajax

first Ill comment my config in server
i have a apache with my html page with angular in 80 port
and other web server in port 4000 listening like a API
i am trying to make a $http request to my server but don't succes, just error message, this is my code
$http.post('http://localhost:4000/tareas', {msg:'asd'}).
success(function(data, status) {
alert('funciono');
}).
error(function(data, status) {
alert('error');
});
my server receive that request because i send a message when a controller is accesed, so the request connect with my API, but always execute the error my request in angular, even with $http.jsonp, that send me the error alert, my server return a simple json.
{data:'hurra.!', status:200}
i need a different response from my server to success?
even with F12 and neetwork, i see the request "canceled" with get and post, but my server send the message so i receive that request. with jsonp, chromium don't say a thin, everything is ok, but the $http.json still send me to error, is because my server response?
thanks to all.

well, searching more i find that cross domain request need "callback=JSON_CALLBACK" in the url and do a jsonp request, so changing my code to
$http.jsonp('http://localhost:4000/tareas?callback=JSON_CALLBACK'}).
success(function(data, status) {
alert('funciono');
}).
error(function(data, status) {
alert('error');
});
do the work and my ajax request now success... i find this in other tread, i put here the link for more info.
parsing JSONP $http.jsonp() response in angular.js
thanks

Related

Monitor network request URL and response content (Throw custom exceptions)

How can network requests be monitored and evaluated for their request URL, parameters, request, and response data?
Desired solution
I want to be notified or being given a custom exception, if specific content occurs in request or response.
Example
Assume a web application with many dynamic Ajax requests. A request or response might contain a broken value, e.g. undefined.
Request URL:
http://localhost:8080/app/?undefined=1
Response JSON data:
{"undefined":"1"}
Attempts
Filtering for request content in Dev Tools is not possible
PostMan tests seem not viable (e.g. no user interactions)
Not tried/found yet
Guesses of what might work ...
Software to intercepts requests and log/alert details
Proxying any URLs on an OS via some standalone application
If importing axios, you could leverage custom interceptors:
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
// Similar functionality can be achieved for request
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
Proxy software
For this case, any proxy that comes with logging ability, or can be extended:
https://mitmproxy.org
https://github.com/http-party/node-http-proxy
Exemplary for many variants under NodeJS
Tunneling
Expose localhost to a domain for testing:
https://ngrok.com
Use the logging capability to get request details:
https://ngrok.com/docs/ngrok-agent/api#list-requests
Localhost vs. 127.0.0.1
localhost should better become 127.0.0.1 or a custom dev domain. On MacOS, localhost did not work with HTTP interceptor browser plugins.

Clicking an href to our Github oAuth endpoint works, but an AJAX request to same endpoint gives a CORS error?

We are trying to implement Github oAuth in our app using Passport.js. If the user hits the endpoint by clicking an anchor tag/href, it works fine, but if we use a click handler to initiate an ajax request instead, we receive a CORS error from the Github server. Why?
Server side code:
app.get('/auth/github',
passport.authenticate('github', { scope: [ 'user:email' ] }));
app.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/login' }),
function(req, res) {
console.log('Github authentication successful!');
res.redirect('/');
});
Client side code (we are using React):
--> Works:
<a href='/auth/github'>Contact</a>;
--> Does Not Work - CORS error:
handleContactAuth(event) {
$.ajax({
url: '/auth/github',
method: 'GET',
success: data => console.log( 'Contact Auth response: ', data),
error: err => console.log( 'Error connecting to GitHub.', err)
});
}
NOTE: This is a click handler on the React component and is functioning fine, as the ajax request is being triggered. I'm aware we're not handling the response currently, apart from just a console.log.
--> CORS Error we see on the Client side when using AJAX method instead of href:
XMLHttpRequest cannot load https://github.com/login/oauth/authorize? response_type=code&redirect_uri=ht…auth%2Fgithub%2Fcallback&scope=user%3Aemail&client_id=our_client_code. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Any ideas? Would appreciate any insights - many thanks.
CORS error is not an error returned by the server, but one triggered by the browser if the response doesn't contain HTTP headers signaling that cross-origin requests are allowed. The endpoint you are hitting obviously isn't designed to be accessed like this.
I had the same problem and I found that at least in Google Chrome XMLHttpRequest object is restricted to same origin policy. So you may need to stick to using an anchor tag.
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
Link: https://developer.chrome.com/extensions/xhr

Inspect HTTP response using a Crossrider extension

According to the Crossrider docs, there is currently a webRequest object with the onRequest event, which allows for accessing the request URI, etc., but I could not find any way to inspect the response data. I was wondering if there is a way to actually inspect the response of that request, such as the response headers and possibly the response data. Thanks for the help.
I'm going out on a limb here but I think your after an AJAX request, in which case you are after the appAPI.request API where you can indeed obtain response and header data. The appAPI.webRequest API is like Chrome's webRequest API used "to observe and analyze traffic and to intercept, block, or modify requests in-flight".
If this is not the case, please can you clarify your scenario.
[RESPONSE TO COMMENT]
Let me first clarify that the webRequest API runs before the requests are made (i.e. the browser is requesting the page but has not yet made the actual HTTP request) and hence it's not relevant to talk of response data.
However, since the URL is provided in the details of the webRequest, you can get the response data and headers yourself using the aforementioned appAPI.request API, as follows:
appAPI.ready(function() {
appAPI.webRequest.monitor.onBeforeNavigate.addListener({
callback: function(details) {
appAPI.request.get({
url: details.requestUrl,
onSuccess: function(response, additionalInfo) {
appAPI.db.async.set(details.requestUrl, {
response: response,
headers: additionalInfo.headers
});
}
});
}
});
});
NOTE: For this example I have used the new webRequest.monitor API designed to be lightweight specifically for monitoring. It's not currently documented (docs should be completed within the next week or so) but you can start using it already for Chrome, Firefox, and Internet Explorer.
[Disclosure: I am a Crossrider employee]

Node authorization and redirect using AJAX post

I am using node and trying to redirect a client after he authorizes himself. For this reason I am using a POST method using ajax on the client side which has the form:
$.ajax({
type: "POST",
url: '/login',
dataType: "json",
async: false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(credentials.username + ":" + credentials.password));
},
data: credentials,
success: function () {
window.alert("Success! (whatever that means)");
}
});
Then on the server side I am trying to redirect to the actual page with the commands
app.get('/login', loginInternalApp);
app.post('/login', function (req, res){
var postContents = req.body;
req.session.username = postContents.username;
res.redirect('/my_secret_page');
});
app.get('/my_secret_page', checkAuth, function (req, res) {
console.log("sending the message!");
res.send('if you are viewing this page it means you are logged in');
res.end();
});
where checkAuth was taken from here how to implement login auth in node.js (instead of user_id I am using username; that's not the problem).
Perhaps what I do not know is how to treat this ajax call correctly. I print some console messages and the server goes all the way to the res.send('if you are viewing this page...') however, nothing happens on the client. Then when I press a control-C to terminate the server, the alert window pops up. Meanwhile, I can see that the function passed on success can have parameters (guessing now: errorCode, errorString, otherData, perhaps more).
So what am I doing wrong?
The issue here is that you are a little confused between the concepts of JavaScript-powered navigation and straight up server request-response powered nav. Let's go through this for a minute and see if it makes more sense.
You are using ajax to submit your login form, which means you stay on the page that you are on, and just submit your http request with JavaScript, collecting the response. You put up the POST, and your server logs the user in, then returns a 3XX indicating a redirect. Your JavaScript collects the response, which you can see if you open up your inspector under the "network" tab. But the page doesn't go anywhere because you are just collecting your response with JavaScript.
In this case, you want to choose one or the other -- use JavaScript to handle your routing (tools like backbone are super useful in cases like these and come with nice routing classes), or submit the login form normally, not through ajax. If you let the form submit when the user hits the button and do not catch it with JS, this should fix the problem - if you return a redirect from the server, the page will redirect as expected. Alternately, if rather than sending a redirect response, you could send back JSON indicating success or failure, then use JavaScript to display the appropriate view, and this would also solve the issue.
Looking at your server-side code, I assume the reason you are using ajax here is in order to set the authorization headers. I'm not sure why you need those, as you hid the internal auth function, but you might see an issue with not using ajax being that you would not have those custom set headers by default in a normal form submission. There are certainly ways to collect the same information and move it in the same ways (you can set headers, delegate to other methods, and even send off http requests from express), but I'd need more details on how specifically you are handling logins to advise on how to streamline that piece : )

handling a redirect from a cross-origin post in AJAX

We are trying to create a RESTful API that will be hosted on server x.foo.com. Client html applications (built in jquery) will be hosted on y.foo.com.
I am dealing with cross-domain issues by setting the Access-Control-Allow-Origin header as described here http://www.w3.org/TR/cors/.
So far so good, and I can now successfully make AJAX calls from host y to host x.
However, I ran into a gotcha with POST requests. The typical response to a post request is a redirect. However, the XMLHttpRequest object will not follow cross domain redirects, thus resulting in a failed call.
// Hosted on y.foo.com
$.ajax({
type: "POST",
url : http://x.foo.com/myapp/",
success: function(data) {
alert("success!");
}
});
// Return status: 302
// (Which errors out in firebug)
Anyone know of any techniques to handle the redirect (to a resource on server x) that I get from this post for a client hosted on y?
How about the client sends a special header for AJAX requests, and depending on whether it's an AJAX request or not, you can change the response instead of doing a redirect.

Resources