Access-Control-Allow-Origin and Angular.js $ http

Whenever I do webapp and I have a CORS problem, I start making coffee. After screwing it in for some time, I manage to get it to work, but this time it is not, and I need help.

Here is the client side code:

$http({method: 'GET', url: 'http://localhost:3000/api/symbol/junk', headers:{ 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With', 'X-Random-Shit':'123123123' }}) .success(function(d){ console.log( "yay" ); }) .error(function(d){ console.log( "nope" ); }); 

The server side is a regular node.js with an express application. I have an extension called cors and it is used with an expression as follows:

 var app = express(); app.configure(function(){ app.use(express.bodyParser()); app.use(app.router); app.use(cors({origin:"*"})); }); app.listen(3000); app.get('/', function(req, res){ res.end("ok"); }); 

If i do

 curl -v -H "Origin: https://github.com" http://localhost:3000/ 

He returns with:

 * Adding handle: conn: 0x7ff991800000 * Adding handle: send: 0 * Adding handle: recv: 0 * Curl_addHandleToPipeline: length: 1 * - Conn 0 (0x7ff991800000) send_pipe: 1, recv_pipe: 0 * About to connect() to localhost port 3000 (#0) * Trying ::1... * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 3000 (#0) > GET / HTTP/1.1 > User-Agent: curl/7.30.0 > Host: localhost:3000 > Accept: */* > Origin: https://github.com > < HTTP/1.1 200 OK < X-Powered-By: Express < Date: Tue, 24 Dec 2013 03:23:40 GMT < Connection: keep-alive < Transfer-Encoding: chunked < * Connection #0 to host localhost left intact ok 

If I run the code on the client side, this will result in an error:

 OPTIONS http://localhost:3000/api/symbol/junk No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. angular.js:7889 XMLHttpRequest cannot load http://localhost:3000/api/symbol/junk. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. localhost/:1 nope 

Checking Chrome Headers:

 Request URL:http://localhost:3000/api/symbol/junk Request Method:OPTIONS Status Code:200 OK Request Headersview source Accept:*/* Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8,es;q=0.6,pt;q=0.4 Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-methods, access-control-allow-headers, x-random-shit Access-Control-Request-Method:GET Cache-Control:max-age=0 Connection:keep-alive Host:localhost:3000 Origin:http://localhost:8000 Referer:http://localhost:8000/ User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 Response Headersview source Allow:GET Connection:keep-alive Content-Length:3 Content-Type:text/html; charset=utf-8 Date:Tue, 24 Dec 2013 03:27:45 GMT X-Powered-By:Express 

Checking the request headers, I see that my X-Random-Shit test line is present in the "Access-Control-Request-Headers" header, but its value is missing. Also, in my head, I expected to see one line for each of the headers that I customize, not blob.

UPDATES ---

I changed my interface to jQuery instead of Angular and made my backend as follows:

 var app = express(); app.configure(function(){ app.use(express.bodyParser()); app.use(app.router); }); app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE'); res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With"); if ('OPTIONS' == req.method){ return res.send(200); } next(); }); app.get('/', function(req, res){ res.end("ok"); }); 

Now it works with GET, but not with anything else (PUT, POST ..).

I will see if any of you find a solution. At the same time, throwing the RESTful concept out of the window and doing everything with GET.

+30
javascript angularjs cors
Dec 24 '13 at 3:31 on
source share
7 answers

I'm new to AngularJS, and I ran into this CORS problem, almost lost my mind! Fortunately, I have found a way to fix this. So here it goes ....

My problem was that when I use the AngularJS $ resource when submitting API requests, I get this XMLHttpRequest cannot load http://website.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. error message XMLHttpRequest cannot load http://website.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. XMLHttpRequest cannot load http://website.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. Yup, I already added callback = "JSON_CALLBACK", and that didn't work.

What I did to fix this problem, instead of using the GET method or resorting to $ http.get, I used JSONP. Just replace the GET method with JSONP and change the api response format to JSONP.

  myApp.factory('myFactory', ['$resource', function($resource) { return $resource( 'http://website.com/api/:apiMethod', { callback: "JSON_CALLBACK", format:'jsonp' }, { method1: { method: 'JSONP', params: { apiMethod: 'hello world' } }, method2: { method: 'JSONP', params: { apiMethod: 'hey ho!' } } } ); }]); 

I hope someone finds this useful. :)

+8
Feb 16 '15 at 11:06
source

I had success with expressing and editing res.header . My mom is very similar to yours, but I have another Allow-Headers , as follows:

 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 

I also use Angular and Node / Express, but I have no headers called in Angular code, only Node / express

+4
Jan 08 '14 at 21:28
source

Adding below to the permitted server server.js

  server.post('/your-rest-endpt/*', function(req,res){ console.log(''); console.log('req.url: '+req.url); console.log('req.headers: '); console.dir(req.headers); console.log('req.body: '); console.dir(req.body); var options = { host: 'restAPI-IP' + ':' + '8080' , protocol: 'http' , pathname: 'your-rest-endpt/' }; console.log('options: '); console.dir(options); var reqUrl = url.format(options); console.log("Forward URL: "+reqUrl); var parsedUrl = url.parse(req.url, true); console.log('parsedUrl: '); console.dir(parsedUrl); var queryParams = parsedUrl.query; var path = parsedUrl.path; var substr = path.substring(path.lastIndexOf("rest/")); console.log('substr: '); console.dir(substr); reqUrl += substr; console.log("Final Forward URL: "+reqUrl); var newHeaders = { }; //Deep-copy it, clone it, but not point to me in shallow way... for (var headerKey in req.headers) { newHeaders[headerKey] = req.headers[headerKey]; }; var newBody = (req.body == null || req.body == undefined ? {} : req.body); if (newHeaders['Content-type'] == null || newHeaders['Content-type'] == undefined) { newHeaders['Content-type'] = 'application/json'; newBody = JSON.stringify(newBody); } var requestOptions = { headers: { 'Content-type': 'application/json' } ,body: newBody ,method: 'POST' }; console.log("server.js : routes to URL : "+ reqUrl); request(reqUrl, requestOptions, function(error, response, body){ if(error) { console.log('The error from Tomcat is --> ' + error.toString()); console.dir(error); //return false; } if (response.statusCode != null && response.statusCode != undefined && response.headers != null && response.headers != undefined) { res.writeHead(response.statusCode, response.headers); } else { //404 Not Found res.writeHead(404); } if (body != null && body != undefined) { res.write(body); } res.end(); }); }); 
+1
Feb 27 '14 at 15:42
source

Writing this middleware can help!

 app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); 

See http://enable-cors.org/server_expressjs.html for more details.

+1
Mar 29 '16 at 8:41
source

@Swapnil Niwane

I managed to solve this problem by calling an ajax request and formatting the data in jsonp.

 $.ajax({ method: 'GET', url: url, defaultHeaders: { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*", 'Accept': 'application/json' }, dataType: 'jsonp', success: function (response) { console.log("success "); console.log(response); }, error: function (xhr) { console.log("error "); console.log(xhr); } }); 
+1
Jan 05 '17 at 16:06 on
source

I found a way to use the JSONP method in $http directly and with params support in the configuration file:

 params = { 'a': b, 'callback': 'JSON_CALLBACK' }; $http({ url: url, method: 'JSONP', params: params }) 
0
May 16 '16 at 10:09
source

Try the following:

  $.ajax({ type: 'POST', url: URL, defaultHeaders: { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*", 'Accept': 'application/json' }, data: obj, dataType: 'json', success: function (response) { // BindTableData(); console.log("success "); alert(response); }, error: function (xhr) { console.log("error "); console.log(xhr); } }); 
-one
Jul 07 '16 at 12:44
source



All Articles