No 'Access-Control-Allow-Origin' header in Angular 2 app












41















For this project, I'm just learning and practicing Angular 2. I have no server-side and am making API requests to
barchart ondemand api .



I'm wondering if it is possible to bypass the cors issue. I'm still fairly new to all this, so baby-step instructions are really appreciated! I'm using http://localhost:8080.



Error message: (api key commented out)



XMLHttpRequest cannot load http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&symbol=GOOG&type=daily&startDate=20150311000000. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.



StockInformationService:



import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class StockInformationService {
private apiRoot = "http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&";

constructor (private _http: Http) {}

getData(symbol: string): Observable<any> {
// Tried adding headers with no luck
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET');
headers.append('Access-Control-Allow-Origin', '*');

return this._http.get(this.apiRoot + "symbol=" + symbol + "&type=daily&startDate=20150311000000", {headers: headers})
.map(response => response.json());
}
}


App Component:



import {Component} from "angular2/core";
import {VolumeComponent} from '../../components/volume/volume';
import {StockInformationService} from '../../core/stock-information.service';

@Component({
selector: 'app-shell',
template: require('./app-shell.html'),
directives: [VolumeComponent],
providers: [StockInformationService]
})
export class AppShell {
constructor(private _stockInformationService: StockInformationService) {}

// In my template, on button click, make api request
requestData(symbol: string) {
this._stockInformationService.getData(symbol)
.subscribe(
data => {
console.log(data)
},
error => console.log("Error: " + error)
)}
}

}


In my console, the requestData Error:
Error: [object Object]










share|improve this question

























  • Could you add what server are you using? this in not angular2 error, but a problem with the CORS configuration of the server, if you said what server are you using, (apache, node+express, etc) you could get a more specific response. I can solve this error with a server with node+express

    – Pablo Ezequiel
    Mar 3 '17 at 2:25
















41















For this project, I'm just learning and practicing Angular 2. I have no server-side and am making API requests to
barchart ondemand api .



I'm wondering if it is possible to bypass the cors issue. I'm still fairly new to all this, so baby-step instructions are really appreciated! I'm using http://localhost:8080.



Error message: (api key commented out)



XMLHttpRequest cannot load http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&symbol=GOOG&type=daily&startDate=20150311000000. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.



StockInformationService:



import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class StockInformationService {
private apiRoot = "http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&";

constructor (private _http: Http) {}

getData(symbol: string): Observable<any> {
// Tried adding headers with no luck
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET');
headers.append('Access-Control-Allow-Origin', '*');

return this._http.get(this.apiRoot + "symbol=" + symbol + "&type=daily&startDate=20150311000000", {headers: headers})
.map(response => response.json());
}
}


App Component:



import {Component} from "angular2/core";
import {VolumeComponent} from '../../components/volume/volume';
import {StockInformationService} from '../../core/stock-information.service';

@Component({
selector: 'app-shell',
template: require('./app-shell.html'),
directives: [VolumeComponent],
providers: [StockInformationService]
})
export class AppShell {
constructor(private _stockInformationService: StockInformationService) {}

// In my template, on button click, make api request
requestData(symbol: string) {
this._stockInformationService.getData(symbol)
.subscribe(
data => {
console.log(data)
},
error => console.log("Error: " + error)
)}
}

}


In my console, the requestData Error:
Error: [object Object]










share|improve this question

























  • Could you add what server are you using? this in not angular2 error, but a problem with the CORS configuration of the server, if you said what server are you using, (apache, node+express, etc) you could get a more specific response. I can solve this error with a server with node+express

    – Pablo Ezequiel
    Mar 3 '17 at 2:25














41












41








41


11






For this project, I'm just learning and practicing Angular 2. I have no server-side and am making API requests to
barchart ondemand api .



I'm wondering if it is possible to bypass the cors issue. I'm still fairly new to all this, so baby-step instructions are really appreciated! I'm using http://localhost:8080.



Error message: (api key commented out)



XMLHttpRequest cannot load http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&symbol=GOOG&type=daily&startDate=20150311000000. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.



StockInformationService:



import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class StockInformationService {
private apiRoot = "http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&";

constructor (private _http: Http) {}

getData(symbol: string): Observable<any> {
// Tried adding headers with no luck
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET');
headers.append('Access-Control-Allow-Origin', '*');

return this._http.get(this.apiRoot + "symbol=" + symbol + "&type=daily&startDate=20150311000000", {headers: headers})
.map(response => response.json());
}
}


App Component:



import {Component} from "angular2/core";
import {VolumeComponent} from '../../components/volume/volume';
import {StockInformationService} from '../../core/stock-information.service';

@Component({
selector: 'app-shell',
template: require('./app-shell.html'),
directives: [VolumeComponent],
providers: [StockInformationService]
})
export class AppShell {
constructor(private _stockInformationService: StockInformationService) {}

// In my template, on button click, make api request
requestData(symbol: string) {
this._stockInformationService.getData(symbol)
.subscribe(
data => {
console.log(data)
},
error => console.log("Error: " + error)
)}
}

}


In my console, the requestData Error:
Error: [object Object]










share|improve this question
















For this project, I'm just learning and practicing Angular 2. I have no server-side and am making API requests to
barchart ondemand api .



I'm wondering if it is possible to bypass the cors issue. I'm still fairly new to all this, so baby-step instructions are really appreciated! I'm using http://localhost:8080.



Error message: (api key commented out)



XMLHttpRequest cannot load http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&symbol=GOOG&type=daily&startDate=20150311000000. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.



StockInformationService:



import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class StockInformationService {
private apiRoot = "http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&";

constructor (private _http: Http) {}

getData(symbol: string): Observable<any> {
// Tried adding headers with no luck
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET');
headers.append('Access-Control-Allow-Origin', '*');

return this._http.get(this.apiRoot + "symbol=" + symbol + "&type=daily&startDate=20150311000000", {headers: headers})
.map(response => response.json());
}
}


App Component:



import {Component} from "angular2/core";
import {VolumeComponent} from '../../components/volume/volume';
import {StockInformationService} from '../../core/stock-information.service';

@Component({
selector: 'app-shell',
template: require('./app-shell.html'),
directives: [VolumeComponent],
providers: [StockInformationService]
})
export class AppShell {
constructor(private _stockInformationService: StockInformationService) {}

// In my template, on button click, make api request
requestData(symbol: string) {
this._stockInformationService.getData(symbol)
.subscribe(
data => {
console.log(data)
},
error => console.log("Error: " + error)
)}
}

}


In my console, the requestData Error:
Error: [object Object]







angular webpack header cors






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 9 at 12:36









Prakash Pazhanisamy

8761923




8761923










asked Mar 15 '16 at 4:05









philip yoophilip yoo

1,35331327




1,35331327













  • Could you add what server are you using? this in not angular2 error, but a problem with the CORS configuration of the server, if you said what server are you using, (apache, node+express, etc) you could get a more specific response. I can solve this error with a server with node+express

    – Pablo Ezequiel
    Mar 3 '17 at 2:25



















  • Could you add what server are you using? this in not angular2 error, but a problem with the CORS configuration of the server, if you said what server are you using, (apache, node+express, etc) you could get a more specific response. I can solve this error with a server with node+express

    – Pablo Ezequiel
    Mar 3 '17 at 2:25

















Could you add what server are you using? this in not angular2 error, but a problem with the CORS configuration of the server, if you said what server are you using, (apache, node+express, etc) you could get a more specific response. I can solve this error with a server with node+express

– Pablo Ezequiel
Mar 3 '17 at 2:25





Could you add what server are you using? this in not angular2 error, but a problem with the CORS configuration of the server, if you said what server are you using, (apache, node+express, etc) you could get a more specific response. I can solve this error with a server with node+express

– Pablo Ezequiel
Mar 3 '17 at 2:25












12 Answers
12






active

oldest

votes


















36














This a problem with the CORS configuration on the server. It is not clear what server are you using, but if you are using Node+express you can solve it with the following code



// Add headers
app.use(function (req, res, next) {

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

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


that code was an answer of @jvandemo to a very similar question.






share|improve this answer





















  • 2





    How to do this in spring boot @Ezequiel?

    – Lahiru Gamage
    Feb 22 '18 at 11:45






  • 4





    Hi @LahiruGamage, @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") worked for me on the request mapping method.

    – Sudheer Kumar
    Apr 3 '18 at 17:15





















16














You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/.



Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
check that you will need to add following in your .htaccess file:



Header set Access-Control-Allow-Origin "*"





share|improve this answer



















  • 15





    what if you're not working with an .htaccess fille?

    – Rafael
    Aug 15 '17 at 13:18











  • Isn't this solution pretty bad through the fact you allow all the domains to controll your backend. What if someone connects to your server and runs a localhost on it? He would be able to get all data out of your backend. Or am I wrong and this is a safe and best practice way to solve this issue?

    – Jonathan Stellwag
    Jun 13 '18 at 10:32



















6














I also had the same issue while using http://www.mocky.io/ what i did is to add in mock.io response header: Access-Control-Allow-Origin *



To add it there just need to click on advanced options



Mock.io Header Example
Once this is done, my application was able to retrieve the data from external domain.






share|improve this answer


























  • Super working for me.

    – Shabbir Dhangot
    Dec 21 '16 at 14:10



















5














Simply you can set in php file as



header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");





share|improve this answer































    4














    Unfortunately, that's not an Angular2 error, that's an error your browser is running into (i.e. outside of your app).



    That CORS header will have to be added to that endpoint on the server before you can make ANY requests.






    share|improve this answer



















    • 5





      Any ideas on how to do that?

      – Rafael
      Aug 15 '17 at 13:22



















    4














    I have spent lot of time for solution and got it worked finally by making changes in the server side.Check the website https://docs.microsoft.com/en-us/aspnet/core/security/cors



    It worked for me when I enabled corse in the server side.We were using Asp.Net core in API and the below code worked



    1) Added Addcors in ConfigureServices of Startup.cs



    public void ConfigureServices(IServiceCollection services)
    {
    services.AddCors();
    services.AddMvc();
    }


    2) Added UseCors in Configure method as below:



    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    app.UseCors(builder =>builder.AllowAnyOrigin());
    app.UseMvc();
    }





    share|improve this answer


























    • Thank you, it was very helpful!

      – Uladzimir Sharyi
      Oct 25 '18 at 13:24











    • I refer this answer for my asp.net web API to solve no-access-control-allow-origin issue.

      – J Sushil
      Nov 21 '18 at 8:47





















    3














    I also encountered the same problem and passed the following way to solve this problem.



    step 1:



    $ npm install --save-dev http-proxy-middleware


    step 2:



    add a proxy when i fetch web api, if you use lite-server you can add a file bs-config.js .



    //file: bs-config.js
    var proxyMiddleware = require('http-proxy-middleware');

    module.exports = {
    server: {
    middleware: {
    1: proxyMiddleware('/example-api', {
    target: 'http://api.example.com',
    changeOrigin: true,
    pathRewrite: {
    '^/news-at-api': '/api'
    }
    })
    }
    }
    };


    hope this helps.






    share|improve this answer

































      1














      If you are creating a mock-up with SoapUI,a free testing tool for REST and SOAP request and response, for Angular 2+ application you should remember to set inside your http header request



       Access-Control-Allow-Origin :  *


      I add two images for helping your insert.
      The first shows the header you should add. If you want to add the header before you have to click the plus button(it's green).



      First image



      The second image shows the insert the *. The value * permits to accept all the request from different hosts.



      Second image



      After this work my Angular application removed this annoying error in my console.



      error inside console



      A big recourse that helped me to understand for creating my first mock up is this video. It will help you for creating a new mock-up inside SoapUi's environment without a server-side.






      share|improve this answer































        1














        I had the same problem when I was practising Angular5. Then I came across https://spring.io/guides/gs/rest-service-cors/ which helped me to resolve the issue.



        I have kept @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") on my request mapping method. We can also configure this globally in spring boot application.






        share|improve this answer

































          0














          Another simple way, without installing anything





          1. HTTP function



            authenticate(credentials) {

            let body = new URLSearchParams();
            body.set('username', credentials.username);
            body.set('password', credentials.password);

            return this.http.post(/rest/myEndpoint, body)
            .subscribe(
            data => this.loginResult = data,
            error => {
            console.log(error);
            },
            () => {
            // function to execute after successfull api call
            }
            );
            }



          2. Create a proxy.conf.json file



            {
            "/rest": {
            "target": "http://endpoint.com:8080/package/",
            "pathRewrite": {
            "^/rest": ""
            },
            "secure": false
            }
            }



          3. then ng serve --proxy-config proxy.conf.json (or)
            open package.json and replace



            "scripts": {
            "start": "ng serve --proxy-config proxy.conf.json",
            },



          and then npm start



          That's it.



          Check here https://webpack.github.io/docs/webpack-dev-server.html for more options






          share|improve this answer































            0














            I got the same error and here how I solved it, by adding the following to your spring controller:



            @CrossOrigin(origins = {"http://localhost:3000"})





            share|improve this answer

































              -1














              Most of the time this happens due to the invalid response type from server.



              Make sure the following 2 to avoid this issue..




              1. You don't need to set any CORS headers in Angular side. it very well know how to deal with it. Angular expects the return data to be in json format. so make sure the return type is JSON even for the OPTIONS request.

              2. You Handle CORS in server side by using CORS header which is very self explanatory or you can google how to set CORS headers or middlewares.






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f36002493%2fno-access-control-allow-origin-header-in-angular-2-app%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                12 Answers
                12






                active

                oldest

                votes








                12 Answers
                12






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                36














                This a problem with the CORS configuration on the server. It is not clear what server are you using, but if you are using Node+express you can solve it with the following code



                // Add headers
                app.use(function (req, res, next) {

                // Website you wish to allow to connect
                res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

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


                that code was an answer of @jvandemo to a very similar question.






                share|improve this answer





















                • 2





                  How to do this in spring boot @Ezequiel?

                  – Lahiru Gamage
                  Feb 22 '18 at 11:45






                • 4





                  Hi @LahiruGamage, @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") worked for me on the request mapping method.

                  – Sudheer Kumar
                  Apr 3 '18 at 17:15


















                36














                This a problem with the CORS configuration on the server. It is not clear what server are you using, but if you are using Node+express you can solve it with the following code



                // Add headers
                app.use(function (req, res, next) {

                // Website you wish to allow to connect
                res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

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


                that code was an answer of @jvandemo to a very similar question.






                share|improve this answer





















                • 2





                  How to do this in spring boot @Ezequiel?

                  – Lahiru Gamage
                  Feb 22 '18 at 11:45






                • 4





                  Hi @LahiruGamage, @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") worked for me on the request mapping method.

                  – Sudheer Kumar
                  Apr 3 '18 at 17:15
















                36












                36








                36







                This a problem with the CORS configuration on the server. It is not clear what server are you using, but if you are using Node+express you can solve it with the following code



                // Add headers
                app.use(function (req, res, next) {

                // Website you wish to allow to connect
                res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

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


                that code was an answer of @jvandemo to a very similar question.






                share|improve this answer















                This a problem with the CORS configuration on the server. It is not clear what server are you using, but if you are using Node+express you can solve it with the following code



                // Add headers
                app.use(function (req, res, next) {

                // Website you wish to allow to connect
                res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

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


                that code was an answer of @jvandemo to a very similar question.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited May 23 '17 at 12:18









                Community

                11




                11










                answered Mar 3 '17 at 2:30









                Pablo EzequielPablo Ezequiel

                1,23221531




                1,23221531








                • 2





                  How to do this in spring boot @Ezequiel?

                  – Lahiru Gamage
                  Feb 22 '18 at 11:45






                • 4





                  Hi @LahiruGamage, @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") worked for me on the request mapping method.

                  – Sudheer Kumar
                  Apr 3 '18 at 17:15
















                • 2





                  How to do this in spring boot @Ezequiel?

                  – Lahiru Gamage
                  Feb 22 '18 at 11:45






                • 4





                  Hi @LahiruGamage, @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") worked for me on the request mapping method.

                  – Sudheer Kumar
                  Apr 3 '18 at 17:15










                2




                2





                How to do this in spring boot @Ezequiel?

                – Lahiru Gamage
                Feb 22 '18 at 11:45





                How to do this in spring boot @Ezequiel?

                – Lahiru Gamage
                Feb 22 '18 at 11:45




                4




                4





                Hi @LahiruGamage, @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") worked for me on the request mapping method.

                – Sudheer Kumar
                Apr 3 '18 at 17:15







                Hi @LahiruGamage, @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") worked for me on the request mapping method.

                – Sudheer Kumar
                Apr 3 '18 at 17:15















                16














                You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/.



                Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
                check that you will need to add following in your .htaccess file:



                Header set Access-Control-Allow-Origin "*"





                share|improve this answer



















                • 15





                  what if you're not working with an .htaccess fille?

                  – Rafael
                  Aug 15 '17 at 13:18











                • Isn't this solution pretty bad through the fact you allow all the domains to controll your backend. What if someone connects to your server and runs a localhost on it? He would be able to get all data out of your backend. Or am I wrong and this is a safe and best practice way to solve this issue?

                  – Jonathan Stellwag
                  Jun 13 '18 at 10:32
















                16














                You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/.



                Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
                check that you will need to add following in your .htaccess file:



                Header set Access-Control-Allow-Origin "*"





                share|improve this answer



















                • 15





                  what if you're not working with an .htaccess fille?

                  – Rafael
                  Aug 15 '17 at 13:18











                • Isn't this solution pretty bad through the fact you allow all the domains to controll your backend. What if someone connects to your server and runs a localhost on it? He would be able to get all data out of your backend. Or am I wrong and this is a safe and best practice way to solve this issue?

                  – Jonathan Stellwag
                  Jun 13 '18 at 10:32














                16












                16








                16







                You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/.



                Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
                check that you will need to add following in your .htaccess file:



                Header set Access-Control-Allow-Origin "*"





                share|improve this answer













                You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/.



                Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
                check that you will need to add following in your .htaccess file:



                Header set Access-Control-Allow-Origin "*"






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 15 '16 at 4:27









                Nitheesh K PNitheesh K P

                713315




                713315








                • 15





                  what if you're not working with an .htaccess fille?

                  – Rafael
                  Aug 15 '17 at 13:18











                • Isn't this solution pretty bad through the fact you allow all the domains to controll your backend. What if someone connects to your server and runs a localhost on it? He would be able to get all data out of your backend. Or am I wrong and this is a safe and best practice way to solve this issue?

                  – Jonathan Stellwag
                  Jun 13 '18 at 10:32














                • 15





                  what if you're not working with an .htaccess fille?

                  – Rafael
                  Aug 15 '17 at 13:18











                • Isn't this solution pretty bad through the fact you allow all the domains to controll your backend. What if someone connects to your server and runs a localhost on it? He would be able to get all data out of your backend. Or am I wrong and this is a safe and best practice way to solve this issue?

                  – Jonathan Stellwag
                  Jun 13 '18 at 10:32








                15




                15





                what if you're not working with an .htaccess fille?

                – Rafael
                Aug 15 '17 at 13:18





                what if you're not working with an .htaccess fille?

                – Rafael
                Aug 15 '17 at 13:18













                Isn't this solution pretty bad through the fact you allow all the domains to controll your backend. What if someone connects to your server and runs a localhost on it? He would be able to get all data out of your backend. Or am I wrong and this is a safe and best practice way to solve this issue?

                – Jonathan Stellwag
                Jun 13 '18 at 10:32





                Isn't this solution pretty bad through the fact you allow all the domains to controll your backend. What if someone connects to your server and runs a localhost on it? He would be able to get all data out of your backend. Or am I wrong and this is a safe and best practice way to solve this issue?

                – Jonathan Stellwag
                Jun 13 '18 at 10:32











                6














                I also had the same issue while using http://www.mocky.io/ what i did is to add in mock.io response header: Access-Control-Allow-Origin *



                To add it there just need to click on advanced options



                Mock.io Header Example
                Once this is done, my application was able to retrieve the data from external domain.






                share|improve this answer


























                • Super working for me.

                  – Shabbir Dhangot
                  Dec 21 '16 at 14:10
















                6














                I also had the same issue while using http://www.mocky.io/ what i did is to add in mock.io response header: Access-Control-Allow-Origin *



                To add it there just need to click on advanced options



                Mock.io Header Example
                Once this is done, my application was able to retrieve the data from external domain.






                share|improve this answer


























                • Super working for me.

                  – Shabbir Dhangot
                  Dec 21 '16 at 14:10














                6












                6








                6







                I also had the same issue while using http://www.mocky.io/ what i did is to add in mock.io response header: Access-Control-Allow-Origin *



                To add it there just need to click on advanced options



                Mock.io Header Example
                Once this is done, my application was able to retrieve the data from external domain.






                share|improve this answer















                I also had the same issue while using http://www.mocky.io/ what i did is to add in mock.io response header: Access-Control-Allow-Origin *



                To add it there just need to click on advanced options



                Mock.io Header Example
                Once this is done, my application was able to retrieve the data from external domain.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 21 '16 at 14:10









                Shabbir Dhangot

                4,98594065




                4,98594065










                answered Aug 6 '16 at 18:09









                AbnerAbner

                3021411




                3021411













                • Super working for me.

                  – Shabbir Dhangot
                  Dec 21 '16 at 14:10



















                • Super working for me.

                  – Shabbir Dhangot
                  Dec 21 '16 at 14:10

















                Super working for me.

                – Shabbir Dhangot
                Dec 21 '16 at 14:10





                Super working for me.

                – Shabbir Dhangot
                Dec 21 '16 at 14:10











                5














                Simply you can set in php file as



                header("Access-Control-Allow-Origin: *");
                header("Content-Type: application/json; charset=UTF-8");





                share|improve this answer




























                  5














                  Simply you can set in php file as



                  header("Access-Control-Allow-Origin: *");
                  header("Content-Type: application/json; charset=UTF-8");





                  share|improve this answer


























                    5












                    5








                    5







                    Simply you can set in php file as



                    header("Access-Control-Allow-Origin: *");
                    header("Content-Type: application/json; charset=UTF-8");





                    share|improve this answer













                    Simply you can set in php file as



                    header("Access-Control-Allow-Origin: *");
                    header("Content-Type: application/json; charset=UTF-8");






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 2 '17 at 6:24









                    Prakash PazhanisamyPrakash Pazhanisamy

                    8761923




                    8761923























                        4














                        Unfortunately, that's not an Angular2 error, that's an error your browser is running into (i.e. outside of your app).



                        That CORS header will have to be added to that endpoint on the server before you can make ANY requests.






                        share|improve this answer



















                        • 5





                          Any ideas on how to do that?

                          – Rafael
                          Aug 15 '17 at 13:22
















                        4














                        Unfortunately, that's not an Angular2 error, that's an error your browser is running into (i.e. outside of your app).



                        That CORS header will have to be added to that endpoint on the server before you can make ANY requests.






                        share|improve this answer



















                        • 5





                          Any ideas on how to do that?

                          – Rafael
                          Aug 15 '17 at 13:22














                        4












                        4








                        4







                        Unfortunately, that's not an Angular2 error, that's an error your browser is running into (i.e. outside of your app).



                        That CORS header will have to be added to that endpoint on the server before you can make ANY requests.






                        share|improve this answer













                        Unfortunately, that's not an Angular2 error, that's an error your browser is running into (i.e. outside of your app).



                        That CORS header will have to be added to that endpoint on the server before you can make ANY requests.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Mar 15 '16 at 4:08









                        drewwyattdrewwyatt

                        2,738104679




                        2,738104679








                        • 5





                          Any ideas on how to do that?

                          – Rafael
                          Aug 15 '17 at 13:22














                        • 5





                          Any ideas on how to do that?

                          – Rafael
                          Aug 15 '17 at 13:22








                        5




                        5





                        Any ideas on how to do that?

                        – Rafael
                        Aug 15 '17 at 13:22





                        Any ideas on how to do that?

                        – Rafael
                        Aug 15 '17 at 13:22











                        4














                        I have spent lot of time for solution and got it worked finally by making changes in the server side.Check the website https://docs.microsoft.com/en-us/aspnet/core/security/cors



                        It worked for me when I enabled corse in the server side.We were using Asp.Net core in API and the below code worked



                        1) Added Addcors in ConfigureServices of Startup.cs



                        public void ConfigureServices(IServiceCollection services)
                        {
                        services.AddCors();
                        services.AddMvc();
                        }


                        2) Added UseCors in Configure method as below:



                        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                        {
                        app.UseCors(builder =>builder.AllowAnyOrigin());
                        app.UseMvc();
                        }





                        share|improve this answer


























                        • Thank you, it was very helpful!

                          – Uladzimir Sharyi
                          Oct 25 '18 at 13:24











                        • I refer this answer for my asp.net web API to solve no-access-control-allow-origin issue.

                          – J Sushil
                          Nov 21 '18 at 8:47


















                        4














                        I have spent lot of time for solution and got it worked finally by making changes in the server side.Check the website https://docs.microsoft.com/en-us/aspnet/core/security/cors



                        It worked for me when I enabled corse in the server side.We were using Asp.Net core in API and the below code worked



                        1) Added Addcors in ConfigureServices of Startup.cs



                        public void ConfigureServices(IServiceCollection services)
                        {
                        services.AddCors();
                        services.AddMvc();
                        }


                        2) Added UseCors in Configure method as below:



                        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                        {
                        app.UseCors(builder =>builder.AllowAnyOrigin());
                        app.UseMvc();
                        }





                        share|improve this answer


























                        • Thank you, it was very helpful!

                          – Uladzimir Sharyi
                          Oct 25 '18 at 13:24











                        • I refer this answer for my asp.net web API to solve no-access-control-allow-origin issue.

                          – J Sushil
                          Nov 21 '18 at 8:47
















                        4












                        4








                        4







                        I have spent lot of time for solution and got it worked finally by making changes in the server side.Check the website https://docs.microsoft.com/en-us/aspnet/core/security/cors



                        It worked for me when I enabled corse in the server side.We were using Asp.Net core in API and the below code worked



                        1) Added Addcors in ConfigureServices of Startup.cs



                        public void ConfigureServices(IServiceCollection services)
                        {
                        services.AddCors();
                        services.AddMvc();
                        }


                        2) Added UseCors in Configure method as below:



                        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                        {
                        app.UseCors(builder =>builder.AllowAnyOrigin());
                        app.UseMvc();
                        }





                        share|improve this answer















                        I have spent lot of time for solution and got it worked finally by making changes in the server side.Check the website https://docs.microsoft.com/en-us/aspnet/core/security/cors



                        It worked for me when I enabled corse in the server side.We were using Asp.Net core in API and the below code worked



                        1) Added Addcors in ConfigureServices of Startup.cs



                        public void ConfigureServices(IServiceCollection services)
                        {
                        services.AddCors();
                        services.AddMvc();
                        }


                        2) Added UseCors in Configure method as below:



                        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                        {
                        app.UseCors(builder =>builder.AllowAnyOrigin());
                        app.UseMvc();
                        }






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Dec 14 '17 at 20:13









                        Broman

                        6,905112342




                        6,905112342










                        answered Dec 14 '17 at 19:52









                        satishsatish

                        372




                        372













                        • Thank you, it was very helpful!

                          – Uladzimir Sharyi
                          Oct 25 '18 at 13:24











                        • I refer this answer for my asp.net web API to solve no-access-control-allow-origin issue.

                          – J Sushil
                          Nov 21 '18 at 8:47





















                        • Thank you, it was very helpful!

                          – Uladzimir Sharyi
                          Oct 25 '18 at 13:24











                        • I refer this answer for my asp.net web API to solve no-access-control-allow-origin issue.

                          – J Sushil
                          Nov 21 '18 at 8:47



















                        Thank you, it was very helpful!

                        – Uladzimir Sharyi
                        Oct 25 '18 at 13:24





                        Thank you, it was very helpful!

                        – Uladzimir Sharyi
                        Oct 25 '18 at 13:24













                        I refer this answer for my asp.net web API to solve no-access-control-allow-origin issue.

                        – J Sushil
                        Nov 21 '18 at 8:47







                        I refer this answer for my asp.net web API to solve no-access-control-allow-origin issue.

                        – J Sushil
                        Nov 21 '18 at 8:47













                        3














                        I also encountered the same problem and passed the following way to solve this problem.



                        step 1:



                        $ npm install --save-dev http-proxy-middleware


                        step 2:



                        add a proxy when i fetch web api, if you use lite-server you can add a file bs-config.js .



                        //file: bs-config.js
                        var proxyMiddleware = require('http-proxy-middleware');

                        module.exports = {
                        server: {
                        middleware: {
                        1: proxyMiddleware('/example-api', {
                        target: 'http://api.example.com',
                        changeOrigin: true,
                        pathRewrite: {
                        '^/news-at-api': '/api'
                        }
                        })
                        }
                        }
                        };


                        hope this helps.






                        share|improve this answer






























                          3














                          I also encountered the same problem and passed the following way to solve this problem.



                          step 1:



                          $ npm install --save-dev http-proxy-middleware


                          step 2:



                          add a proxy when i fetch web api, if you use lite-server you can add a file bs-config.js .



                          //file: bs-config.js
                          var proxyMiddleware = require('http-proxy-middleware');

                          module.exports = {
                          server: {
                          middleware: {
                          1: proxyMiddleware('/example-api', {
                          target: 'http://api.example.com',
                          changeOrigin: true,
                          pathRewrite: {
                          '^/news-at-api': '/api'
                          }
                          })
                          }
                          }
                          };


                          hope this helps.






                          share|improve this answer




























                            3












                            3








                            3







                            I also encountered the same problem and passed the following way to solve this problem.



                            step 1:



                            $ npm install --save-dev http-proxy-middleware


                            step 2:



                            add a proxy when i fetch web api, if you use lite-server you can add a file bs-config.js .



                            //file: bs-config.js
                            var proxyMiddleware = require('http-proxy-middleware');

                            module.exports = {
                            server: {
                            middleware: {
                            1: proxyMiddleware('/example-api', {
                            target: 'http://api.example.com',
                            changeOrigin: true,
                            pathRewrite: {
                            '^/news-at-api': '/api'
                            }
                            })
                            }
                            }
                            };


                            hope this helps.






                            share|improve this answer















                            I also encountered the same problem and passed the following way to solve this problem.



                            step 1:



                            $ npm install --save-dev http-proxy-middleware


                            step 2:



                            add a proxy when i fetch web api, if you use lite-server you can add a file bs-config.js .



                            //file: bs-config.js
                            var proxyMiddleware = require('http-proxy-middleware');

                            module.exports = {
                            server: {
                            middleware: {
                            1: proxyMiddleware('/example-api', {
                            target: 'http://api.example.com',
                            changeOrigin: true,
                            pathRewrite: {
                            '^/news-at-api': '/api'
                            }
                            })
                            }
                            }
                            };


                            hope this helps.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jun 20 '16 at 8:48









                            Vojtech Ruzicka

                            9,055154449




                            9,055154449










                            answered Jun 20 '16 at 8:45









                            JunJun

                            312




                            312























                                1














                                If you are creating a mock-up with SoapUI,a free testing tool for REST and SOAP request and response, for Angular 2+ application you should remember to set inside your http header request



                                 Access-Control-Allow-Origin :  *


                                I add two images for helping your insert.
                                The first shows the header you should add. If you want to add the header before you have to click the plus button(it's green).



                                First image



                                The second image shows the insert the *. The value * permits to accept all the request from different hosts.



                                Second image



                                After this work my Angular application removed this annoying error in my console.



                                error inside console



                                A big recourse that helped me to understand for creating my first mock up is this video. It will help you for creating a new mock-up inside SoapUi's environment without a server-side.






                                share|improve this answer




























                                  1














                                  If you are creating a mock-up with SoapUI,a free testing tool for REST and SOAP request and response, for Angular 2+ application you should remember to set inside your http header request



                                   Access-Control-Allow-Origin :  *


                                  I add two images for helping your insert.
                                  The first shows the header you should add. If you want to add the header before you have to click the plus button(it's green).



                                  First image



                                  The second image shows the insert the *. The value * permits to accept all the request from different hosts.



                                  Second image



                                  After this work my Angular application removed this annoying error in my console.



                                  error inside console



                                  A big recourse that helped me to understand for creating my first mock up is this video. It will help you for creating a new mock-up inside SoapUi's environment without a server-side.






                                  share|improve this answer


























                                    1












                                    1








                                    1







                                    If you are creating a mock-up with SoapUI,a free testing tool for REST and SOAP request and response, for Angular 2+ application you should remember to set inside your http header request



                                     Access-Control-Allow-Origin :  *


                                    I add two images for helping your insert.
                                    The first shows the header you should add. If you want to add the header before you have to click the plus button(it's green).



                                    First image



                                    The second image shows the insert the *. The value * permits to accept all the request from different hosts.



                                    Second image



                                    After this work my Angular application removed this annoying error in my console.



                                    error inside console



                                    A big recourse that helped me to understand for creating my first mock up is this video. It will help you for creating a new mock-up inside SoapUi's environment without a server-side.






                                    share|improve this answer













                                    If you are creating a mock-up with SoapUI,a free testing tool for REST and SOAP request and response, for Angular 2+ application you should remember to set inside your http header request



                                     Access-Control-Allow-Origin :  *


                                    I add two images for helping your insert.
                                    The first shows the header you should add. If you want to add the header before you have to click the plus button(it's green).



                                    First image



                                    The second image shows the insert the *. The value * permits to accept all the request from different hosts.



                                    Second image



                                    After this work my Angular application removed this annoying error in my console.



                                    error inside console



                                    A big recourse that helped me to understand for creating my first mock up is this video. It will help you for creating a new mock-up inside SoapUi's environment without a server-side.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Sep 4 '17 at 14:02









                                    Luca BasilicoLuca Basilico

                                    1568




                                    1568























                                        1














                                        I had the same problem when I was practising Angular5. Then I came across https://spring.io/guides/gs/rest-service-cors/ which helped me to resolve the issue.



                                        I have kept @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") on my request mapping method. We can also configure this globally in spring boot application.






                                        share|improve this answer






























                                          1














                                          I had the same problem when I was practising Angular5. Then I came across https://spring.io/guides/gs/rest-service-cors/ which helped me to resolve the issue.



                                          I have kept @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") on my request mapping method. We can also configure this globally in spring boot application.






                                          share|improve this answer




























                                            1












                                            1








                                            1







                                            I had the same problem when I was practising Angular5. Then I came across https://spring.io/guides/gs/rest-service-cors/ which helped me to resolve the issue.



                                            I have kept @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") on my request mapping method. We can also configure this globally in spring boot application.






                                            share|improve this answer















                                            I had the same problem when I was practising Angular5. Then I came across https://spring.io/guides/gs/rest-service-cors/ which helped me to resolve the issue.



                                            I have kept @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") on my request mapping method. We can also configure this globally in spring boot application.







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Apr 9 '18 at 13:18









                                            Jakob Pennington

                                            53




                                            53










                                            answered Apr 3 '18 at 17:19









                                            Sudheer KumarSudheer Kumar

                                            3331518




                                            3331518























                                                0














                                                Another simple way, without installing anything





                                                1. HTTP function



                                                  authenticate(credentials) {

                                                  let body = new URLSearchParams();
                                                  body.set('username', credentials.username);
                                                  body.set('password', credentials.password);

                                                  return this.http.post(/rest/myEndpoint, body)
                                                  .subscribe(
                                                  data => this.loginResult = data,
                                                  error => {
                                                  console.log(error);
                                                  },
                                                  () => {
                                                  // function to execute after successfull api call
                                                  }
                                                  );
                                                  }



                                                2. Create a proxy.conf.json file



                                                  {
                                                  "/rest": {
                                                  "target": "http://endpoint.com:8080/package/",
                                                  "pathRewrite": {
                                                  "^/rest": ""
                                                  },
                                                  "secure": false
                                                  }
                                                  }



                                                3. then ng serve --proxy-config proxy.conf.json (or)
                                                  open package.json and replace



                                                  "scripts": {
                                                  "start": "ng serve --proxy-config proxy.conf.json",
                                                  },



                                                and then npm start



                                                That's it.



                                                Check here https://webpack.github.io/docs/webpack-dev-server.html for more options






                                                share|improve this answer




























                                                  0














                                                  Another simple way, without installing anything





                                                  1. HTTP function



                                                    authenticate(credentials) {

                                                    let body = new URLSearchParams();
                                                    body.set('username', credentials.username);
                                                    body.set('password', credentials.password);

                                                    return this.http.post(/rest/myEndpoint, body)
                                                    .subscribe(
                                                    data => this.loginResult = data,
                                                    error => {
                                                    console.log(error);
                                                    },
                                                    () => {
                                                    // function to execute after successfull api call
                                                    }
                                                    );
                                                    }



                                                  2. Create a proxy.conf.json file



                                                    {
                                                    "/rest": {
                                                    "target": "http://endpoint.com:8080/package/",
                                                    "pathRewrite": {
                                                    "^/rest": ""
                                                    },
                                                    "secure": false
                                                    }
                                                    }



                                                  3. then ng serve --proxy-config proxy.conf.json (or)
                                                    open package.json and replace



                                                    "scripts": {
                                                    "start": "ng serve --proxy-config proxy.conf.json",
                                                    },



                                                  and then npm start



                                                  That's it.



                                                  Check here https://webpack.github.io/docs/webpack-dev-server.html for more options






                                                  share|improve this answer


























                                                    0












                                                    0








                                                    0







                                                    Another simple way, without installing anything





                                                    1. HTTP function



                                                      authenticate(credentials) {

                                                      let body = new URLSearchParams();
                                                      body.set('username', credentials.username);
                                                      body.set('password', credentials.password);

                                                      return this.http.post(/rest/myEndpoint, body)
                                                      .subscribe(
                                                      data => this.loginResult = data,
                                                      error => {
                                                      console.log(error);
                                                      },
                                                      () => {
                                                      // function to execute after successfull api call
                                                      }
                                                      );
                                                      }



                                                    2. Create a proxy.conf.json file



                                                      {
                                                      "/rest": {
                                                      "target": "http://endpoint.com:8080/package/",
                                                      "pathRewrite": {
                                                      "^/rest": ""
                                                      },
                                                      "secure": false
                                                      }
                                                      }



                                                    3. then ng serve --proxy-config proxy.conf.json (or)
                                                      open package.json and replace



                                                      "scripts": {
                                                      "start": "ng serve --proxy-config proxy.conf.json",
                                                      },



                                                    and then npm start



                                                    That's it.



                                                    Check here https://webpack.github.io/docs/webpack-dev-server.html for more options






                                                    share|improve this answer













                                                    Another simple way, without installing anything





                                                    1. HTTP function



                                                      authenticate(credentials) {

                                                      let body = new URLSearchParams();
                                                      body.set('username', credentials.username);
                                                      body.set('password', credentials.password);

                                                      return this.http.post(/rest/myEndpoint, body)
                                                      .subscribe(
                                                      data => this.loginResult = data,
                                                      error => {
                                                      console.log(error);
                                                      },
                                                      () => {
                                                      // function to execute after successfull api call
                                                      }
                                                      );
                                                      }



                                                    2. Create a proxy.conf.json file



                                                      {
                                                      "/rest": {
                                                      "target": "http://endpoint.com:8080/package/",
                                                      "pathRewrite": {
                                                      "^/rest": ""
                                                      },
                                                      "secure": false
                                                      }
                                                      }



                                                    3. then ng serve --proxy-config proxy.conf.json (or)
                                                      open package.json and replace



                                                      "scripts": {
                                                      "start": "ng serve --proxy-config proxy.conf.json",
                                                      },



                                                    and then npm start



                                                    That's it.



                                                    Check here https://webpack.github.io/docs/webpack-dev-server.html for more options







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Apr 12 '17 at 6:12









                                                    SibirajSibiraj

                                                    2,08121538




                                                    2,08121538























                                                        0














                                                        I got the same error and here how I solved it, by adding the following to your spring controller:



                                                        @CrossOrigin(origins = {"http://localhost:3000"})





                                                        share|improve this answer






























                                                          0














                                                          I got the same error and here how I solved it, by adding the following to your spring controller:



                                                          @CrossOrigin(origins = {"http://localhost:3000"})





                                                          share|improve this answer




























                                                            0












                                                            0








                                                            0







                                                            I got the same error and here how I solved it, by adding the following to your spring controller:



                                                            @CrossOrigin(origins = {"http://localhost:3000"})





                                                            share|improve this answer















                                                            I got the same error and here how I solved it, by adding the following to your spring controller:



                                                            @CrossOrigin(origins = {"http://localhost:3000"})






                                                            share|improve this answer














                                                            share|improve this answer



                                                            share|improve this answer








                                                            edited Nov 22 '17 at 18:28









                                                            Jason Aller

                                                            3,06192932




                                                            3,06192932










                                                            answered Nov 22 '17 at 15:34









                                                            Moh-OthmanovicMoh-Othmanovic

                                                            12




                                                            12























                                                                -1














                                                                Most of the time this happens due to the invalid response type from server.



                                                                Make sure the following 2 to avoid this issue..




                                                                1. You don't need to set any CORS headers in Angular side. it very well know how to deal with it. Angular expects the return data to be in json format. so make sure the return type is JSON even for the OPTIONS request.

                                                                2. You Handle CORS in server side by using CORS header which is very self explanatory or you can google how to set CORS headers or middlewares.






                                                                share|improve this answer




























                                                                  -1














                                                                  Most of the time this happens due to the invalid response type from server.



                                                                  Make sure the following 2 to avoid this issue..




                                                                  1. You don't need to set any CORS headers in Angular side. it very well know how to deal with it. Angular expects the return data to be in json format. so make sure the return type is JSON even for the OPTIONS request.

                                                                  2. You Handle CORS in server side by using CORS header which is very self explanatory or you can google how to set CORS headers or middlewares.






                                                                  share|improve this answer


























                                                                    -1












                                                                    -1








                                                                    -1







                                                                    Most of the time this happens due to the invalid response type from server.



                                                                    Make sure the following 2 to avoid this issue..




                                                                    1. You don't need to set any CORS headers in Angular side. it very well know how to deal with it. Angular expects the return data to be in json format. so make sure the return type is JSON even for the OPTIONS request.

                                                                    2. You Handle CORS in server side by using CORS header which is very self explanatory or you can google how to set CORS headers or middlewares.






                                                                    share|improve this answer













                                                                    Most of the time this happens due to the invalid response type from server.



                                                                    Make sure the following 2 to avoid this issue..




                                                                    1. You don't need to set any CORS headers in Angular side. it very well know how to deal with it. Angular expects the return data to be in json format. so make sure the return type is JSON even for the OPTIONS request.

                                                                    2. You Handle CORS in server side by using CORS header which is very self explanatory or you can google how to set CORS headers or middlewares.







                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Nov 7 '18 at 5:17









                                                                    Rameez RamiRameez Rami

                                                                    2,0641321




                                                                    2,0641321






























                                                                        draft saved

                                                                        draft discarded




















































                                                                        Thanks for contributing an answer to Stack Overflow!


                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                        But avoid



                                                                        • Asking for help, clarification, or responding to other answers.

                                                                        • Making statements based on opinion; back them up with references or personal experience.


                                                                        To learn more, see our tips on writing great answers.




                                                                        draft saved


                                                                        draft discarded














                                                                        StackExchange.ready(
                                                                        function () {
                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f36002493%2fno-access-control-allow-origin-header-in-angular-2-app%23new-answer', 'question_page');
                                                                        }
                                                                        );

                                                                        Post as a guest















                                                                        Required, but never shown





















































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown

































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown







                                                                        Popular posts from this blog

                                                                        Monofisismo

                                                                        Angular Downloading a file using contenturl with Basic Authentication

                                                                        Olmecas