The ‘Access-Control-Allow-Origin’ header contains multiple values

[Origin]: https://stackoverflow.com/questions/37594403/the-access-control-allow-origin-header-contains-multiple-values

i’m trying to send get request to api like it’s a login url

var url = "http://demo.software.travel/gptp/api/authorization?apiKey=****&alias=****&login=****&password=****"
$.get(url, function(data) {
    console.log(data);
});

i’m getting this in my console this error

XMLHttpRequest cannot load http://demo.software.travel/gptp/api/authorization?apiKey=****&alias=****&login=****&password=****. 
The 'Access-Control-Allow-Origin' header contains multiple values 'http://travellights.net, *', but only one is allowed. 
Origin 'http://travellights.net' is therefore not allowed access.

i’m trying to see questions here to solve it but i didn’t get what i need to change, this is annoying actually.

The ‘Access-Control-Allow-Origin’ header contains multiple values

this solved by asp.net web.congif

By the way i’m using CHROME BROWSER any help i appreciate.

UPDATE response headers:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:origin, x-requested-with, Content-Type, accept, Token
Access-Control-Allow-Methods:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
Access-Control-Allow-Origin:http://travellights.net
Access-Control-Allow-Origin:*
Connection:close
Content-Encoding:gzip
Content-Type:application/json;charset=utf-8
Date:Thu, 02 Jun 2016 16:41:18 GMT
Server:nginx/1.1.19
Set-Cookie:JSESSIONID=51FEE1A1206B9B481DD3EEA4167A9256; Path=/gptp
Vary:Origin
Vary:Accept-Encoding
X-UA-Compatible:IE=EmulateIE7

Request Headers:

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ar;q=0.6,en-GB;q=0.4
Connection:keep-alive
Host:demo.software.travel
Origin:http://travellights.net
Referer:http://travellights.net/b2b/Pages/login?
User-Agent:Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
shareedit

You are attempting to do Cross-origin resource sharing (CORS) which is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated. (such as accessing fonts or JSON files).

Browsers restrict your access to resources from other origins as of Same-origin policy as a security measure for internet users.

To get around this issue you have to options:

  1. allow CORS on the domain http://demo.software.travel (but there is are security concerns, more description about it here: https://www.owasp.org/index.php/HTML5_Security_Cheat_Sheet#Cross_Origin_Resource_Sharing)

Enable CORS on the server to be able to access other domains through. this can be done by adding the following headers to responses:

Access-Control-Allow-Origin: http://travellights.net Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
  1. if you are not granted resource sharing with that domain, you are allowed to use JSONP for read only operations (JSONP is inherently read-only)

JSONP wraps a JSON object in a callback, which technically makes the request a non-restricted resource (a script tag) hence can be shared across domains.

it can be done via vanilla js by adding a script tag onto the page.

function process(data) {
    // do stuff with JSON
}

var script = document.createElement('script');
script.src = '//domainURL?callback=process'

document.getElementsByTagName('head')[0].appendChild(script);

or you can use jquery to achieve the same:

$.ajax({enter code here
    url: "http://query.yahooapis.com/v1/public/yql",
    jsonp: "callback",
    dataType: "jsonp",
    data: {
        q: "select title,abstract,url from search.news where query=\"cat\"",
        format: "json"
    },
    success: function( response ) {
        console.log( response ); // server response
    }
});

jquery documentation: https://learn.jquery.com/ajax/working-with-jsonp/

shareedit

If you set “Full” CORS (with OPTION pre-request) on in nginx by add ‘access-control-allow-origin *’ and independently you add that header (for Simple CORS – without OPTION pre-request) to each response in SERVER (eg. php):

header('Access-Control-Allow-Origin', "*");

Then you will get this problem. Solution: remove code which add this header in server if already you add this header in your nginx config 🙂

I found this advice here

shareedit
Advertisements

Why does my JavaScript get a “No ‘Access-Control-Allow-Origin’ header is present on the requested resource” error when Postman does not?

[Origin]: https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present

I am trying to do authorization using JavaScript by connecting to the RESTful API built in Flask. However, when I make the request, I get the following error:

XMLHttpRequest cannot load http://myApiUrl/login. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.

I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?

This is the request code:

$.ajax({
    type: "POST",
    dataType: 'text',
    url: api,
    username: 'user',
    password: 'pass',
    crossDomain : true,
    xhrFields: {
        withCredentials: true
    }
})
    .done(function( data ) {
        console.log("done");
    })
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
        alert(textStatus);
    });

If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

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.

shareedit
shareedit

For C# web services – webapi

Please add the following code in your web.config file under <system.webServer> tag. This will work.

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

Please make sure you are not doing any mistake in the Ajax call.

jQuery

$.ajax({
    url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    type: "POST", /* or type:"GET" or type:"PUT" */
    dataType: "json",
    data: {
    },
    success: function (result) {
        console.log(result);
    },
    error: function () {
        console.log("error");
    }
});

Angular 4 issue, please refer to How to fix Angular 4 API call issues.

shareedit

Why use angular’s $log instead of console.log?

[Origin]: https://stackoverflow.com/questions/24185847/why-use-angulars-log-instead-of-console-log

I understand it is a best practice in angular to use $log instead of console.log. However, I can’t find good documentation explaining the reasons. Why should a developer use $log?

$log first checks if the browser supports console.log (IE 8, for example, doesn’t). This prevents errors being displayed on IE 8. Note: this doesn’t mean it will log anything on IE 8, it simply means it won’t throw the error.

Next to that, it also allows you to decorate and mock $log for extending and testing purposes, if you are so inclined. You could for example decorate it to log to an array for IE 8 support.

A bonus feature: if you pass it a JavaScript Error instance, it will attempt to format it nicely. This can be found out by reading the source code.

EDIT: “It is not that IE 8 doesn’t support console.log. It just doesn’t create the console object until the dev tools are opened.” See comments below for more details.

how to solve error “[$location:nobase] $location in HTML5 mode requires a tag to be present!”

[Origin]: https://stackoverflow.com/questions/40121747/how-to-solve-error-locationnobase-location-in-html5-mode-requires-a-base

I have no idea how to solve this case.

Error: [$location:nobase] $location in HTML5 mode requires a tag to be present!
http://errors.angularjs.org/1.5.7/$location/nobase at angular.js:68 at $LocationProvider.$get 
(angular.js:13384) at Object.invoke (angular.js:4709) at angular.js:4508 at getService 
(angular.js:4655) at injectionArgs (angular.js:4679) at Object.invoke (angular.js:4701) at 
angular.js:4508 at getService (angular.js:4655) at injectionArgs (angular.js:4679)

This happens when you have set html5mode, like so :

$locationProvider.html5Mode({
 enabled: true,
 requireBase: false
});

Just add a tag in your HTML template like so :

<head>
 <base href="/">
 ...
</head>

It’s exactly same thing mentioned in the docs here: https://docs.angularjs.org/error/$location/nobase

shareedit

AngularJS: Difference between Service vs Provider vs Factory

[Origin]: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

by 

If you are searching for this it’s probably because you are trying to figure out which one is the right one for you to use. Or because you’ve come across the three of them and are trying to determine the difference because they seem similar.

If you think they are similar – you’re right. They are very similar. In fact, they are all the the same thing.

They are all providers. The factory and the service are just special cases of the provider, but you can accomplish everything you want using just provider. I’ll show you.

The Provider

We’re going to create a provider that returns a value and simply display that value, you would do this:

<body ng-app="MyModule">
    <div ng-controller="MyController></div>
</body>
var mod = angular.module("MyModule", []);

mod.provider("myProvider", function() {
    this.$get = function() {
        return "My Value";
    };
});

mod.controller("MyController", function(myProvider) {
    console.log("MyController - myProvider: " + myProvider);
});
CONSOLE OUTPUT
MyController - myProvider: My Value

A working interactive example can be found at: JS Fiddle.

There, so a “provider” at the core let’s you “provide” a value. That value could be anything. In this case it’s a string with a value of “My Value” but it could easily have been a function or an object.

Note in further code samples I’m going to exclude the <body> tag and the definition of the mod for the purpose of keeping the code excerpts short and to the point.

Angular only gets the value once – ever

Note that angular only “gets” the value once, no matter how many times the provider is injected. That means it calls $get() only once ever, stores the value provided by $get(), and gives you that same stored value every time.

To show you what I mean I’ll create another controller and inject the provider again with a console statement so that you can see what’s happening.

<div ng-controller="MyController"></div>
<div ng-controller="MyController2"></div>
mod.provider("myProvider", function() {
    this.$get = function() {
        console.log("MyProviderFunction.$get() called."); // ADDED this line
        return "My Value";
    };
});

mod.controller("MyController", function(myProvider) {
    console.log("MyController - myProvider: " + myProvider);
});

mod.controller("MyController2", function(myProvider) { // ADDED this controller
    console.log("MyController2 - myProvider: " + myProvider);
});
CONSOLE OUTPUT
MyProviderFunction.$get() called.
MyController - myProvider: My Value
MyController2 - myProvider: My Value

Open in JS Fiddle

As you can see the $get() function was only called once.

Note that we wrote a bunch of code for the provider only for the purpose of creating a method called $get(). Why not instead of giving angular a function that defines another function, why not just give it the function we want to run directly instead? Well you can, that’s what Angular calls a factory.

A Factory

With a factory you just provide the function body for the $get method and Angular does the rest. Below is what the new code looks like, as you will see it behaves exactly the same.

mod.factory("myProvider", function() { // CHANGED “provider" to “factory"
    console.log("Factory function called.");
    return "My Value";
});

mod.controller("MyController", function(myProvider) {
    console.log("MyController - myProvider: " + myProvider);
});

mod.controller("MyController2", function(myProvider) {
    console.log("MyController2 - myProvider: " + myProvider);
});
CONSOLE OUTPUT
Factory function called.
MyController - myProvider: My Value
MyController2 - myProvider: My Value

Open in JS Fiddle

Now you might be wondering why would you ever use a provider if you can accomplish the same thing with a factory with less code. There are a couple of reasons and I’ll go into that later, right now I want to stay true to the title of this post and address the difference between these two (provider and factory) and a service.

So far we’ve returned a simple string value, but in practice what we probably want to return most of the time is an object. Well that wouldn’t change our example very much we can very easily swap out the string we’re returning with an object instead.

For example let’s do that by returning an object that contains a function called getValue(). Now there are several ways you can create an object in JavaScript, we’re going to use the “Object Constructor” approach where we create a function that populates an object with properties and functions and uses the new keyword to instantiate it.

function MyObject() { // ADDED our object constructor
    this.getValue = function() {
        return "My Value";
    };
}

mod.factory("myProvider", function() {
    console.log("Factory function called.");
    return new MyObject(); // CREATE an instance of our object
});

mod.controller("MyController", function(myProvider) {
    console.log("MyController - myProvider: " + myProvider.getValue()); // CHANGED to call getValue()
});

mod.controller("MyController2", function(myProvider) {
    console.log("MyController2 - myProvider: " + myProvider.getValue()); // CHANGED to call getValue()
});
CONSOLE OUTPUT
Factory function called.
MyController - myProvider: My Value
MyController2 - myProvider: My Value

Open in JS Fiddle

Now I want to make one small tweak to this because it will lead nicely into the next concept. In our example we create the “Object Constructor” function MyObject(), but since we’re only instantiating it in one place we can use an anonymous function instead.

This is a very small tweak. Instead of this:

function MyObject() {
    this.getValue = function() {
        return "My Value";
    };
}

mod.factory("myProvider", function() {
    console.log("Factory function called.");
    return new MyObject();
});

We do this:

mod.factory("myProvider", function() {
    console.log("Factory function called.");
    return new function() { // INLINED our object constructor
        this.getValue = function() {
            return "My Value";
        };
    };
});

So the whole thing now looks like this:

mod.factory("myProvider", function() {
    console.log("Factory function called.");
    return new function() { // INLINED our object constructor
        this.getValue = function() {
            return "My Value";
        };
    };
});

mod.controller("MyController", function(myProvider) {
    console.log("MyController - myProvider: " + myProvider.getValue());
});

mod.controller("MyController2", function(myProvider) {
    console.log("MyController2 - myProvider: " + myProvider.getValue());
});

Open in JS Fiddle

Now since our whole factory is made up of a single object, wouldn’t it be nice if we could just give Angular the object constructor function instead of having to write that funky looking factory. Well you are in luck, this is exactly what a service is.

At your Service

Here is that same code except using a service instead of a factory.

mod.service("myProvider", function() { // CHANGED "factory" to "service"
    // NOTE that the only function being passed is the object constructor from before
    this.getValue = function() {
        return "My Value";
    };
});

mod.controller("MyController", function(myProvider) {
    console.log("MyController - myProvider: " + myProvider.getValue());
});

mod.controller("MyController2", function(myProvider) {
    console.log("MyController2 - myProvider: " + myProvider.getValue());
});
CONSOLE OUTPUT
MyController - myProvider: My Value
MyController2 - myProvider: My Value

Open in JS Fiddle

Provider vs Factory vs Service

So in summary, providerfactory, and service are all providers. A factory is a special case of a provider when all you need in your provider is a $get() function. It allows you to write it with less code. A service is a special case of a factory when you want to return an instance of a new object, with the same benefit of writing less code.

When to use one versus the other?

The answer is you use the most specialize version that accomplishes your goal. Say for example you are returning an existing object defined somewhere else that takes constructor arguments. You can’t pass arguments to the service, so you would make the call with a factory instead.

mod.factory("myProvider", function() {
    console.log("Factory function called.");
    return new SomeMessageBoxClass("custom argument");
});

One of the main factors of deciding between a provider and factory is whether you want to be able to configure the object that is generated before it’s generated. You do this by calling module.config() and getting an instance to the provider itself (instead of the object returned by the provider). You do this by appending “Provider” to the end of your provider’s name when you are injecting it.

Here is an example of how you would do that:

mod.provider("myProvider", function() {
    this.value = "My Value";

    this.setValue = function(newValue) {
        this.value = newValue;
    };

    this.$get = function() {
        return this.value;
    };
});

mod.controller("MyController", function(myProvider) {
    console.log("MyController - myProvider: " + myProvider);
});

mod.config(function(myProviderProvider) { // ADDED config section
    // Note the extra "Provider" suffix
    myProviderProvider.setValue("New Value");
});

That covers when to use the three providers: providerfactory, and service. There is one additional provider that was not mentioned here that is yet another special case and that’s the value provider.

If you remember when we first introduced the factory provider above we gave the simple example of returning a string value. That looked like this:

mod.factory("myProvider", function() {
    return "My Value";
});

Well we could have actually done that using the value provider instead, again the benefit being that you can do it in less code. The code below does the same thing as the code above:

mod.value("myProvider", "My Value");

So when would you use one versus the other? Presumably you would use the factoryprovider when you want to calculate the value based on some other data, for example data from another value provider or an external source. And/or when you want to calculate the value if and only when it’s first requested. Here are some examples:

// Example where factory depends on a "value" provider
mod.value("multiple", 3);
mod.factory("value", function(multiple) { 
    return 10 * multiple; 
});
// Example where factory depends on external data
mod.factory("value", function(multiple) { 
    var multiple = getDateFromExternalPage();
    return 10 * multiple; 
});

Did I imply that value was the only other provider? Well I lied, there is another that is very similar to value with two minor differences. That provider is called constant.

The difference between value and constant is that a value specified using constant is available during the configuration phase. You might remember from earlier that I mentioned that provider was accessible from the configuration phase, but service and factorywere not.

Well it’s the same for value and constantconstant is available from the configuration phase and value is not. The other difference is as the name implies you can’t change the value of a constant. The first value you assign it is the value it keeps, if you try to assign it a different value later it will be ignored.

Here’s an example:

mod.value("myValue", "First Assignment");
mod.value("myValue", "Second  Assignment");
mod.constant("myConstant", "First Assignment");
mod.constant("myConstant", "Second Assignment");

mod.controller("MyController", function(myValue, myConstant) {
    console.log("myValue: " + myValue);
    console.log("myConstant: " + myConstant);
});
CONSOLE OUTPUT
myValue: Second Assignment
myConstant: First Assignment

Here is a summary of when to use each:

value You are providing a simple literal value.
mod.value("myValue", 10);
constant You need to be able access that value during the configuration phase. (using .config())
mod.constant("myValue", 10);
mod.config(function(myValue) {
    console.log(myValue);
});
factory The value you are providing needs to be calculated based on other data.
mod.factory("myFactory", function() {
    return 10;
});
service You are returning an object with methods.
mod.service("myService", function() {
    var name = "Bob";
    this.setName = function(newName) {
        this.name = newName;
    };
    this.getName = function() {
        return this.name;
    }
});
provider You want to be able to configure, during the config phase, the object that is going to be created before it’s created.
mod.provider("greeter", function() {
    var name;

    this.setName = function(newName) {
        name = newName;
    };

    this.$get = function() {
        return new function() {
            this.sayHi = function() {
                console.log("Hi " + name;
            };
        };
    };
});

mod.config(function(greeterProvider) {
    greeterProvider.setName(“John");
});
        

To drive the point home one last time here is a image of a provider with the factory, value, and service portions highlighted:

An image of an AngularJS provider with the factory, value, and service portions highlighted.

angularjs-provider-service-factory-highlight-examples

If you found this useful and want to take it with you you can download a formatted PDF cheat sheet by filling out the popup on this page or clicking here: Get the AngularJS provider cheat sheet

AngularJS and its use of Dollar Variables

[Origin]: https://stackoverflow.com/questions/12648543/angularjs-and-its-use-of-dollar-variables

Does anyone know if the reasoning behind the use of dollar methods and variables in angularJS is to instruct angularJS to avoid checking those values when a digestion is going on? So, if angular comes across $scope.$value and $scope.value, then it will avoid checking the former since it’s prefixed with a dollar character in its variable name?

shareedit

There are a few times Angular ignores variables prefixed with the dollar sign:

  1. In Schumli’s comment below, where json filters will not output them
  2. When using the {{ }} directive, angular will not show nested $ variables. For example this only displays the visible property.
    ng-init="n = { visible: 'foo', $ignore: 'bar' };">{{ n }}
  3. Additionally when adding an explicit watcher on a scope object, changes to properties with a leading dollar sign of this object will not trigger the watcher. See this updated fiddle.
  4. angular.equals() ignores keys prefixed with $.
shareedit

How to output html through AngularJS template?

[Origin]: https://stackoverflow.com/questions/19770156/how-to-output-html-through-angularjs-template

<h1>{{ revision.title }}</h1>

<div ng-bind-html="revision.content"></div>

The title outputs fine, but the content – doesn’t. It’s got some html in it and I get the following error: Attempting to use an unsafe value in a safe context. which is being described as so: http://docs.angularjs.org/error/$sce:unsafe and that’s fine, but then how can I output the content as there will be some html in it and so I must set it to {{ revision.content | safe }} or smthn. What is the correct way?

EDIT:

AngularJS version: 1.2

shareedit

So the fix is this:

include angular-sanitize.min.js from http://code.angularjs.org/ and include it in your module:

var app = angular.module('app', ['ngSanitize']);

and then you’re free to use ng-bind-html

shareedit