2

I have a list of key value pair of urls and I am accessing them in function named accessUrl. The urls which we hit are external urls and not maintained by us, i.e. I can't change the server code which sends us the response back from those urls

http.get() on success gives me status and response.

var accessUrl = function(){
  $.each(url, function(key, value)
  {
      $http.get(value).success(function(response,status){

      $scope.status=status;
      if($scope.status == "200"){
           versionMap[key]=response.version;
           setColor[key]='color-green';
           //console.log("map "+versionMap[key]);
        }
    })//end of success

       .error(function(err){
          versionMap[key]="Down";
          setColor[key]='color-red';
        })//end of error
  })//end of each loop
}//end of accessUrl

I am trying to make a cross origin request. At present I have CORS extension added to Chrome.

My app.js:

var express = require("express");
var app     = express();
var path    = require("path");

app.use("/", express.static(__dirname));

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.htm'));
  //__dirname : It will resolve to your project folder.
});

app.set('port', process.env.PORT);
console.log(port);

I do not want to use the CORS extension anymore. Without the extension I encountered the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://myurl.com (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Is there a way by which we can write code in Angular to make CORS requests or any other method?

I have gone through the answers suggested at:

Yet, I couldn’t figure out what's needed.

Community
  • 1
  • 1
kamini
  • 65
  • 1
  • 9

4 Answers4

0

add these headers to your node js server

var express = require("express");
 var app = express();
 var path = require("path");

 app.use("/", express.static(__dirname));

 app.get('/', function(req, res) {
     res.sendFile(path.join(__dirname + '/index.htm'));
     //__dirname : It will resolve to your project folder.
 });

 app.use(function(req, res, next) {

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

     // Pass to next layer of middleware
     next();
 });

 app.set('port', process.env.PORT);
 console.log(port);
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
  • Thanks for your answer. But adding these headers didn't help. Also, since we are hitting end points which are not on our server(we are making api get calls). I didn't understand how does adding these headers change anything? Because from what I understand, our app.js is just to render the html page and this would have helped if we were getting the response from a page we have hosted? – kamini Apr 17 '17 at 06:18
0

First inject httpProvider in your config and then include the following line in your app.js

$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

It will work like a charm.

Mohit Shah
  • 178
  • 1
  • 8
0

You can use cors library in your server after that you wont need to add/send any special headers with your GET/POST requests just add these 2 lines in your file: Method 1:

var cors = require('cors');
app.use(cors());

after installing it using npm:

npm install cors --save

Method2:

In case you don't want to use additional libraries you can add headers manually in you server file as:

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

Method 3:

In case you dont want to edit your server side code till the development process you can use this CORS chrome extension which does the work perfectly. P.S: you might have to disable it to access other sites like google/youtube etc.

warl0ck
  • 3,356
  • 4
  • 27
  • 57
  • Thanks for your response. Method 1 does not work, it still shows the same errors. And method 2 is something I would want to escape as mentioned in the question. – kamini Apr 17 '17 at 07:55
  • method 1 works fine for me have you installed it first `npm install cors --save` – warl0ck Apr 17 '17 at 09:17
  • if it still doesn't work please check the updated method2, in which you are appending headers manually which should also work fine. – warl0ck Apr 17 '17 at 09:19
0

External API need to mention which origin can call the API. If your domain name is not defined in the external API, then you cannot access the API. This is the security feature. The only way to solve this is to ask your external API provider to allow your host name.

This can be done using 'Access-Control-Allow-Origin' header. Your external API has to send a header with 'Access-Control-Allow-Origin' as key and your host name as value. There is no other way to bypass this.

elango.dev
  • 124
  • 1
  • 6