Skip to content

Instantly share code, notes, and snippets.

@dirkk0
Created July 10, 2013 15:24
Show Gist options
  • Save dirkk0/5967221 to your computer and use it in GitHub Desktop.
Save dirkk0/5967221 to your computer and use it in GitHub Desktop.
Enabling CORS in Angular JS with NodeJS/Express
// in AngularJS (client)
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
// in Express/nodeJS
// in NodeJS/Express (server)
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
next();
});
@atul221282
Copy link

Hi Thanks for sharing your Solution but in my case my chrome browser still showing two calls one from angular and one from other under Initiator column. im using it with .Net mvc4.

@mikeerickson
Copy link

So, I am curious here... I have an issue where AngularJS simply wont allow CORS access to the server (I have tried $http and Restangular).

However, in my case I am ONLY setting the 'Access-Control-Allow-Origin' header? Are the other two indeed required as well? I have always been under impression that ACAO was only one required?

@krishna81m
Copy link

krishna81m commented Jun 8, 2017

Thanks for the post, and for all other Java servers

`package com.rk.angular.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CORSFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	HttpServletResponse httpResponse = (HttpServletResponse) response;
	httpResponse.addHeader("Access-Control-Allow-Origin", "*");
	// headers.add("Access-Control-Allow-Origin", // "http://podcastpedia.org"); //allows CORS requests only coming from podcastpedia.org
	httpResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
	httpResponse.addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia");
           chain.doFilter(request, response);
}

@Override
public void destroy() {

}

}
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment